user18810119
user18810119

Reputation:

Formating string

how can I format this string to 2 places after dot in .NET:

My string: 224.39000000000001 What I want to get: 224.39

Also it has to be a String. I don't want to parse it or convert it

I've tried with:

String.Format(Data[i].Number, "%.2f")

but it does not working

Upvotes: 0

Views: 45

Answers (1)

Hans Kesting
Hans Kesting

Reputation: 39284

If your "Number" property is of type string, then you cannot format it as a number. Either convert it to a number and then format, OR find the position of the . and use a substring:

var s = "224.39000000000001";
var i = s.IndexOf('.');
if (i >= 0  && i < s.Length-2)
{
  // found a '.' so just use up to that + 2 extra characters
  Console.WriteLine(s.Substring(0, i+3));
}
else
{
  // no '.' found, so just take all
  Console.WriteLine(s);
}

You can of course wrap this in a method returning the trimmed string, so you can call it from anywhere.

EDIT
Also guard against less than 2 characters after the ., such as "244.4".

Upvotes: 2

Related Questions