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?
Converting a string to a decimal value or decimal equivalent can be done using the Decimal. TryParse() method. It converts the string representation of a number to its decimal equivalent.
Round(temp, 2); Alternatively, if you want the result as a string, just parse it and format it to two decimal places: double temp = Double.
You CAN convert any number to String with, for instance, Long. toString(long l) .
If you are converting price (in string) to decimal price then.... from decimal import Decimal price = "14000,45" price_in_decimal = Decimal(price. replace(',','. '))
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With