简体   繁体   中英

C# show 6 decimals returns wrong value

C# Console application. I have the following code:

next = 758550
next = (double)next / Math.Pow(10, 6);
file.WriteLine(next);

Instead of returning 0.758550 it returns 0.75855 (without the zero at the end) even though I specified it to be double.

Yes, double doesn't preserve trailing zeroes. It's meant to be a type which is about the magnitude of values, not the precise decimal digits.

However, decimal does retain trailing zeroes, so if you write:

decimal next = 758550m;
next = next * 0.000001m;
file.WriteLine(next);

... that will show you what you want. Interestingly, dividing by 1000000 doesn't work here. I suspect the algorithm is something along the lines of "retain as many insignificant decimal digits as are in either operand", but it's not entirely clear.

Alternatively, you can specify a custom format for your double value instead:

file.WriteLine(next.ToString("0.000000"));

or:

file.WriteLine("{0:0.000000}", next);

You should really work out which type is most appropriate to you. As a rule of thumb, "artificial" values - especially currency - are most appropriately represented as decimal . "Natural" values - such as distances, weights etc - are most appropriately represented as double .

Because there is no difference in 0.758550 and 0.75855 , the last 0 is insignificant. You an specify format to get last zero.

string strForDisplay = next.ToString("0.0000000");

The above will give you the last 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM