Converting string "2 1/2" to double

  • Thread starter Thread starter Bruce Wood
  • Start date Start date
B

Bruce Wood

Nope. There's nothing in the Framework.

I wrote my own Fraction class, which I would be happy to share with
you. I'll send a message to you directly.
 
Is there a C# class that will help convert strings that include fractions
( "2 1/2" e.g.) to doubles ? Convert.ToDouble() throws an invalid input
format exception.

Obviously I can write code to do it but this seems like a fairly normal
thing to want to do and I would expect C# to have already built in support.

Can anyone help? Even unmanaged code would do.

Brian Hough
 
Looks like you've got an offer of code already but I'll give a hint to
anyone that wants to figure this out themselves.

using System.Text.RegularExpressions;

split the number into an integer and a fraction by using the space
between them, split the numerator and denominator by using the "/"
between them, divide the numerator by the denominator, then add the integer.

in Perl this could be done like so; (the regular expression will be
similar in C#, that is why I am showing you this)

my $fraction = "2 1/2";
my ($int, $num, $den) = $fraction =~ m|(\d+) (\d+)/(\d+)|;
print $int + ($num/$den);

this prints "2.5". In Perl variable types are pretty insignificant, its
smart enough to know when you need a double, and it auto converts. Perl
makes you LAZY, don't use it unless you need development speed.

Enough about Perl.

the bit between the "m|" and the "|" will be important to you.

jeremiah();
 
Can you send them to me to? Just concatenate the string to get my email
(trying to avoid spam)

"rene_el" + "" + "izondo@sbc" + "" + global.net"
 
Hello!

Bruce Wood wrote:
[...snip...]
I wrote my own Fraction class, which I would be happy to share with
you. I'll send a message to you directly.

I've been looking for a decent "Fraction" class for a while now. Is there
any chance you'd send your code to me, too ?
 
Back
Top