.NET: decimal rounded string

If I have decimal , how can I get a lowercase version with two decimal places? This does not work:

 Math.Round(myDecimal, 2).ToString("{0.00}"); 
+4
source share
3 answers

Do not use curly braces, they are intended to embed a formatted value in a longer string using string.Format . Use this:

 myDecimal.ToString("0.00"); 
+8
source

Maybe I'm wrong, but I tried myDecimal.ToString(); and it worked.

+2
source

Assuming myDecimal is System.Decimal , then Math.Round(myDecimal, 2).ToString(); will display two decimal digits of precision, as you wish, without any format string (unless the absolute value of your number is greater than 10 ^ 27-1). This is because the decimal data type preserves the full precision of the number. That is, 1m , 1.0m and 1.00m are stored differently and will be displayed differently.

Note that this does not apply to float or double . 1f , 1.0f and 1.00f are saved and displayed the same way as 1d , 1.0d and 1.00d .

Since the format string should be parsed at runtime, I would probably omit it in most cases for code like this.

0
source

Source: https://habr.com/ru/post/1299462/


All Articles