0

I'm have a hard time trying to format a float with 4 decimal places, for example, I have the number 2.999995, I wanna get only 4 decimal places from this number, 2.9999, when I use .toString("#.####") or .toString("0.0000") it return 2.3000, I don't wanna this, I wanna 2.9999, someone can help me?

Thanks

1 Answers1

-2

Try This:

float floatVal = 2.999995f;
string str=floatVal.ToString();
if(str.Split('.')[1].Length > 3)
    floatVal=Convert.ToSingle(str.Substring(0,str.IndexOf('.')+5));

Console.WriteLine(floatVal);

Output:

2.9999

Demo here

Sudhakar Tillapudi
  • 25,935
  • 5
  • 37
  • 67