Main Site Documentation

Parse and round double number


#1

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?


#2

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


#3

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


#4

Double.Parse() has also other bug:

http://netmf.codeplex.com/workitem/788


#5

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;


#6

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.


#7

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


#8

@ 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…


#9

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


#10

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