Doing a Math.Round(x,2) on a decimal value, but need to ensure 2 numbers after decimal as its money

坚强是说给别人听的谎言 提交于 2020-01-14 14:52:13

问题


Some values are returning 2.0 but I need it to be 2.00 as this is a money value that is displayed to the web page.

I am doing:

Math.Round(value, 2);

Is there a way to force it to 2 numbers after the decimal?


回答1:


You should be using a decimal to store monetary values.

But regardless of whether you are using a decimal or floating point type, your question asks how the number can be displayed with two decimal places. Use money.ToString("0.00") to display two decimal places.




回答2:


If your using VB.Net use

FormatNumber(number, digitsAfter)

or

FormatCurrency(number, digitsAfter)

or this can be in both (C# and Vb.Net)

doubleNumber = -1898300.1987;
Console.WriteLine(doubleNumber.ToString("F2", CultureInfo.InvariantCulture));  
// Displays -1898300.20

See this link for the full ToString() formats: http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx




回答3:


Either .ToString("0.00") as Mark suggested if you only need to display .00 or Math.Round(value * 100.0) / 100.0; if you need an actual value with cent accuracy.



来源:https://stackoverflow.com/questions/2375735/doing-a-math-roundx-2-on-a-decimal-value-but-need-to-ensure-2-numbers-after-d

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