Parse and round double number

Hi,

I need to convert a string to a double number. The usual double.Parse method returns approximation of the value. As I went through the forum here, I found the solution to be


int precision = 100000;//I want 5 digits after the decimal
double value = exMath.Truncate(double.Parse(STRING) * precision) / precision;

The code works exactly as expected with the Microsoft Emulator, the string “0.03375” yields the value 0,03375. When I run the same code in the ChipworkX, however, I get the value 0,03374. Am i missing something?

You can take that line apart so you can step through the code to see where it goes wrong


double value = double.Parse(STRING);
value *= precision;
value = exMath.Truncate(value);
value /= precision;

Also you can replace value = exMath.Truncate(value) with value = (int)value

We are looking into the problem. We will get back to you.

Double.Parse() has also other bug:

[url]http://netmf.codeplex.com/workitem/788[/url]

For everyone having my problem, here is a workaround I’m going to use:


            int precision= 100000;
            double  value = double.Parse(STRING) * precision;
            value = System.Math.Round(value);
            value /= precision;

This is not a bug. It’s just not possible for a double to hold an exact representation of that number. See: http://support.microsoft.com/kb/42980/en-us

So Math.Round is the right function to use here.

I have actually been through this before… However double precision on number smaller than 1 should yield correct for this recursive number. .net has a similar problem with numbers 0 to -1and Microsoft does have a problem with recursive .3333 or .6666. That said we don’t stand much chance do we.

Cheers Ian

@ Wouter
Yes, I am aware of the way float numbers are stored in the memory. I know an approximation of the number is being stored. What got me wondering is why executing the same code on the emulator and ChipworkX yields different results. After all they are both using NETMF…

The emulator will, of course, use an FPU.

Just for kicks, according to those linux nerds the real test is 3 / 7. It should be

0.42857142857142857142857142857143. What does the chipworkX come up with?

Cheers Ian

Oh, didn’t realize that. Everything’s clear then :slight_smile:
Thanks for the help.