Reputation: 582
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?
Upvotes: 6
Views: 25667
Reputation: 98740
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 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.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.
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
Upvotes: 7
Reputation: 20754
There are two different concepts here.
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
Upvotes: 5
Reputation: 51
the thing that works for me in my case is num.ToString("#######.###")
Upvotes: 0
Reputation: 160
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);
Upvotes: -2