0

I have a calculator application.

How do I achieve the following?

  1. If there are non-zero numbers after the decimal, then it should stay as double.

  2. If there is NO non-zero number after the decimal, it should be converted to the integer equivalent of double.

    For Example, 10.0003 should be displayed as 10.0003. Where as 10.0 should be displayed as 10.

Currently I display all the results as Double (10.0). How can I check if there are any non-zero numbers after the decimal? Do we have a simple solution?

4

2 回答 2

1

floating point numbers are not represented exactly and accurately in the machine. They are not fixed point. So 10.0 may be actually 9.99999988451 or something similar. Or, 10.0003 may actually be 10.0000228993 - so it is extremely hard to write a logic that satisfies this.

please read What every computer scientist must know about floating point numbers

于 2013-03-31T03:42:29.680 回答
0
x is a double  
y = round(x)  
if (x - y == 0) 
{
   // x has no non-zero decimal
}
else
{
   // x has non-zero decimal
}
于 2013-03-31T03:46:50.370 回答