Home > Mobile >  Formating string
Formating string

Time:06-08

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

CodePudding user response:

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)
{
  // 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.

  • Related