开发者

Formatting a double as a string correctly in C#?

开发者 https://www.devze.com 2023-02-06 09:29 出处:网络
I want to print out the string represenation of a double without losing precision using ToString()I get the following when I tr开发者_Go百科y formatting it as a string:

I want to print out the string represenation of a double without losing precision using ToString() I get the following when I tr开发者_Go百科y formatting it as a string:

double i = 101535479557522.5; 
i.ToString(); //displays 101535479557523

How do I do this in C#?


If you want it to be exactly the same you should use i.ToString("r") (the "r" is for round-trip). You can read about the different numeric formats on MSDN.


You're running into the limits of the precision of Double. From the docs:

Remember that a floating-point number can only approximate a decimal number, and that the precision of a floating-point number determines how accurately that number approximates a decimal number. By default, a Double value contains 15 decimal digits of precision, although a maximum of 17 digits is maintained internally.

If you want more precision - and particularly maintaining a decimal representation - you should look at using the decimal type instead.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号