Libor Zapletal
Libor Zapletal

Reputation: 14102

C# Convert double to string cut some last numbers

I have latitude and longitude in double and I want to convert them to string format with dot. So I am using:

start_lon.ToString(CultureInfo.InvariantCulture)

and I get right format (I get dot) but I find out that sometimes I am missing some of the last numbers. Why is it happening? For example I got number 16.597571661711296 and I get this string "16.5975716617113". I know it's "rounding-off" (not sure if it's the right word in english) the number but why? And how can I fix this?

Upvotes: 0

Views: 1134

Answers (4)

sommmen
sommmen

Reputation: 7628

Note for future readers, you can use the Round trip format specifier to always get the most appropriate digits:

By default, the return value only contains 15 digits of precision although a maximum of 17 digits is maintained internally. If the value of this instance has greater than 15 digits, ToString returns PositiveInfinitySymbol or NegativeInfinitySymbol instead of the expected number. If you require more precision, specify format with the "G17" format specification, which always returns 17 digits of precision, or "R", which returns 15 digits if the number can be represented with that precision or 17 digits if the number can only be represented with maximum precision.

MSDN Double.ToString Method

string valueString = initialValue.ToString("R", CultureInfo.InvariantCulture);

This works for doubles as well as floats/singles.

Upvotes: 1

oleksii
oleksii

Reputation: 35905

And how can I fix this?

Use decimal type instead of the double

decimal n = 16.597571661711296M;
// This writes: 16.597571661711296
Console.WriteLine(n.ToString("G", CultureInfo.InvariantCulture)); 

Upvotes: 0

Viacheslav Smityukh
Viacheslav Smityukh

Reputation: 5843

The number format contains a number of a decimal digits, so you should change it to be sure that you will get required result.

var nfi = (System.Globalization.NumberFormatInfo)System.Globalization.CultureInfo.InvariantCulture.NumberFormat.Clone();
nfi.NumberDecimalDigits = xxx;

start_lon.ToString(nfi);

Upvotes: 1

Toon Casteele
Toon Casteele

Reputation: 2579

double has a precision of 15-16 digits. That's why it's rounding to that number.

more info here http://msdn.microsoft.com/en-us/library/678hzkk9(v=vs.71).aspx

Upvotes: 1

Related Questions