william007
william007

Reputation: 18525

Convert string to 2 decimal place

I have a string (confirm to be of decimal expression) 0.4351242134

I want to convert to a string with two decimal place 0.44

How should I do in C#?

Upvotes: 12

Views: 102162

Answers (9)

esenkaya
esenkaya

Reputation: 398

If you need only one line of code;

decimal strdec = strvar != null ? decimal.Round(decimal.Parse(strvar), 2) : 0m;

Upvotes: 0

Syed ali abbas shah
Syed ali abbas shah

Reputation: 1

Convert.ToDecimal(Value).ToString("N2")

Upvotes: 0

Gustav
Gustav

Reputation: 55816

First, you must parse using a culture or you may loose the decimals. Next, you must have a text result to have a fixed count of decimals. Finally, you round to two decimals, but ToString() can do that for you, thus:

string amount5 = "2.509"; // should be parsed as 2.51

decimal decimalValue = Decimal.Parse(amount5, System.Globalization.CultureInfo.InvariantCulture);
string textValue = decimalValue.ToString("0.00");

// 2.51

Upvotes: 3

Enkode
Enkode

Reputation: 4783

float myNumber = float.Parse("0.4351242134");
Console.WriteLine(string.Format("{0:f2}", myNumber ));

https://msdn.microsoft.com/en-us/library/s8s7t687.aspx

Upvotes: 2

Rohit
Rohit

Reputation: 10236

Would this help

double ValBefore= 0.4351242134;
double ValAfter= Math.Round(ValBefore, 2, MidpointRounding.AwayFromZero); //Rounds"up"

Upvotes: 1

Renatas M.
Renatas M.

Reputation: 11820

Well I would do:

var d = "0.4351242134";
Console.WriteLine(decimal.Parse(d).ToString("N2"));

Upvotes: 10

Ilya Ivanov
Ilya Ivanov

Reputation: 23626

var probablyDecimalString = "0.4351242134";
decimal value;
if (Decimal.TryParse(probablyDecimalString , out value))
    Console.WriteLine ( value.ToString("0.##") );
else
    Console.WriteLine ("not a Decimal");

Upvotes: 15

Mharlin
Mharlin

Reputation: 1705

var d = decimal.Parse("0.4351242134");
Console.WriteLine(decimal.Round(d, 2));

Upvotes: 10

Zak
Zak

Reputation: 734

float f = float.Parse("0.4351242134");
Console.WriteLine(string.Format("{0:0.00}", f));

See this for string.Format.

Upvotes: 2

Related Questions