Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string to decimal with 3 decimal places?

Tags:

c#

.net

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?

like image 998
Bhavin Bhaskaran Avatar asked Jun 10 '15 11:06

Bhavin Bhaskaran


People also ask

How do you convert string to decimal?

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.

How do you convert a string to two decimal places?

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.

How do you convert a decimal to a long string?

You CAN convert any number to String with, for instance, Long. toString(long l) .

How do you convert string to decimal in Python?

If you are converting price (in string) to decimal price then.... from decimal import Decimal price = "14000,45" price_in_decimal = Decimal(price. replace(',','. '))


2 Answers

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
like image 121
Soner Gönül Avatar answered Oct 07 '22 03:10

Soner Gönül


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

like image 22
Hamid Pourjam Avatar answered Oct 07 '22 04:10

Hamid Pourjam