how to convert string to decimal upto 3 places?
my string will be like this
striing aa = "22.333"
string bb = "22"
string cc = "22.4444"
how to convert this to decimal
how to convert string to decimal upto 3 places?
my string will be like this
striing aa = "22.333"
string bb = "22"
string cc = "22.4444"
how to convert this to decimal
You can convert and round in one line - and one line to take care of localization:
string cc = "22.4444";
IFormatProvider provider = System.Globalization.CultureInfo.InvariantCulture;
decimal ccDecimal = Math.Round(Convert.ToDecimal(cc,provider), 3);
Will return 22.444
.
You can do it with decimal.Parse (ToDecimal) Method: https://msdn.microsoft.com/de-de/library/hf9z3s65%28v=vs.110%29.aspx
string value = "22.333";
decimal d = decimal.Parse(s);
First you can convert your String to a Decimal Value:
var convertDecimal = Convert.ToDecimal(value);
Afterwards you can round it up, if it is longer:
https://msdn.microsoft.com/en-us/library/system.math.round(v=vs.110).aspx
As far as i know, you cant "convert" the String to a decimal with 3 Positions, if its smaller, because it is saved with the zeros anyway
3 places can be achieved with Math.Round
. Safest string conversion would be the TryParse
method:
string srcString = "123.45123";
decimal outDecimal;
if (decimal.TryParse(srcString, out outDecimal))
{
// conversion is successful, so you can use outDecimal variable
outDecimal = decimal.Round(outDecimal, 3, MidpointRounding.AwayFromZero);
}
You could doing something like this
string aa = "22.333";
string bb = "22";
string cc = "22.4444";
decimal d = decimal.Parse(aa);
decimal e = decimal.Parse(bb);
decimal f = decimal.Parse(cc);
Console.WriteLine(string.Format("{0:0.000}", d));
Console.WriteLine(string.Format("{0:0.000}", e));
Console.WriteLine(string.Format("{0:0.000}", f));
try it
string value;
decimal number;
value = "1,643.57";
if (Decimal.TryParse(value, out number))
Console.WriteLine(number);
else
Console.WriteLine("Unable to parse '{0}'.", value);