Math.Round not keeping the trailing zero

不打扰是莪最后的温柔 提交于 2019-12-19 13:48:14

问题


I need all values to rounded to two decimal places. So 1.401 should round to 1.40, but Math.Round(value, 2) rounds to 1.4.

How can I force the trailing zero?


回答1:


1.4 is the same as 1.40 - you just want to display it differently. Use a format string when calling ToString - like value.ToString("0.00")




回答2:


1.4 == 1.40 the only time you'd ever need a trailing 0 is when you display the number..i.e. format it to string.

.ToString("N2");



回答3:


I know this is an old question, but might help someone!

I am using a c# xml class to populate and then serialise to xml. One of the values is a double. If I assign a '7' to the value this gets serialised to '7' when I actually need '7.00'. Easiest way round this was just to do:

foo = doubleValue + 0.00M

And that makes the value 7.00 instead of just 7. Thought this was better then doing a ToString and then parsing it back.




回答4:


The trailing zero is more of a formatting than a value issue, so use

foo.ToString("0.00")



回答5:


The trailing zero is just a presentation. Math-wise, 1.40 and 1.4 are equivalent.

Use formatting instead to present it with the 2 decimal places:

String.Format("{0:0.00}", 1.4);

or

yourNumber.ToString("0.00");



回答6:


It is a number (double?), so it doesn't have a trailing zero - you have to make it text and force a trailing zero.




回答7:


It has to do with whether you use a decimal or a double.

While internally (as it appears from the Source Code) Math.Round() preserves the trailing zeros even on a double, still the fact that it is saved as a double in memory causes automatically to remove all trailing zeros

So if you do want tailing zeros, you can either use the string display functions to format it as others have answered, or make sure to pass in the original value as a decimal (causing to use internally Decimal.Math.Round which will deal only with decimals), and make sure to not cast the result to a double and also not to save it in a double variable.

Similarly if you have a decimal and you don't want trailing zeros, just cast it to a double (you can either cast the input to Math.Round or the result, it doesn't matter as long as somewhere in the way it is becoming a double).



来源:https://stackoverflow.com/questions/12307630/math-round-not-keeping-the-trailing-zero

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