Cris
Cris

Reputation: 4044

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.

Upvotes: 2

Views: 203

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1504142

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.

Upvotes: 7

Habib
Habib

Reputation: 223422

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

Upvotes: 2

Related Questions