问题
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