C# float trouble. Why 1000000 + 0.10f = 1000000?

喜你入骨 提交于 2021-02-17 06:20:14

问题


Why

Console.WriteLine((1000000f + 0.10f).ToString("N2"));

print

1 000 000.00

but no 1 000 000.10?

When I use type "double" or type "float" less 1000000 - this problem disappears!


回答1:


Use decimal to prevent those accuracy/rounding issues.

Console.WriteLine((1000000m + 0.10m).ToString("N2"));

Reason: float has only a accuracy of 7 digits (reference) - your number has 8




回答2:


According to MSDN, float type has only 7 digits precision. One milion has 7 digits, decimal part is rounded.

Double type has 15 - 16 digits precision, so milion can have 8 - 9 digits long decimal part. Number less than one milion has less than 7 digits (without decimal part).



来源:https://stackoverflow.com/questions/42271635/c-sharp-float-trouble-why-1000000-0-10f-1000000

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!