简体   繁体   中英

How to convert string to decimal with 3 decimal places?

string num = 23.6;

I want to know how can I convert it into decimal with 3 decimal places like

decimal nn = 23.600 

Is there any method?

I try my best..

First of all your string num = 23.6; won't even compile. You need to use double quotes with your strings like string num = "23.6";

If you wanna get this as a decimal , you need to parse it first with a IFormatProvider that have . as a NumberDecimalSeparator like InvariantCulture (if your CurrentCulture uses . already, you don't have to pass second paramter);

decimal nn = decimal.Parse(num, CultureInfo.InvariantCulture);

Now we have a 23.6 as a decimal value. But as a value, 23.6 , 23.60 , 23.600 and 23.60000000000 are totally same, right? No matter which one you parse it to decimal, you will get the same value as a 23.6M in debugger. Looks like these are not true. See Jon Skeet comments on this answer and his "Keeping zeroes" section on Decimal floating point in .NET article.

Now what? Yes, we need to get it's textual representation as 23.600 . Since we need only decimal separator in a textual representation, The "F" Format Specifier will fits out needs.

string str = nn.ToString("F3", CultureInfo.InvariantCulture); // 23.600

There are two different concepts here.

  1. Value
  2. View

you can have a value of 1 and view it like 1.0 or 1.0000 or +000001.00 .

you have string 23.6 . you can convert it to decimal using var d = decimal.Parse("23.6")

now you have a value equals to 23.6 you can view it like 23.600 by using d.ToString("F3")

you can read more about formatting decimal values

在我的情况下对我有用的东西是num.ToString(“#######。###”)

A decimal is not a string, it does not display the trailing zeros. If you want a string that displays your 3 decimal places including trailing zeros, you can use string.Format:

decimal nn= 23.5;
var formattedNumber = string.Format("{0,000}", nn);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM