How to round float in c#

3k Views Asked by At

I want to get number, which .ToString() conversion total lenght <= 7. For example

 1. 1.23456789     - > 1.23457 
 2. 12345.789      - > 12345.8
 3. 123456789.1234 - > 1.235E8
 4. 0.00001234 - > 1.23E-8

I want to use realy fast solution, because work with big file.

This code can solve part of this problem, but it dont work

                    int power = (int)Math.Log10(f) + 1;
                    f = f / (float)Math.Pow(10, power);
                    f = (float)Math.Round(f, 5);
                    f = f * (float)Math.Pow(10, power);

For example f = 7.174593E+10 after rounding it become 0.71746 (fine for me)

and when i multiplie it by 10^11 it become 7.17459948E+10

but i expected 7.71746E+10

UPD. As result i want to get string, not a number.

2

There are 2 best solutions below

3
On BEST ANSWER

If all you are going to use it for is to display it as string (as said in the update) then use String.format().

//one of these should output it correctly the other uses the wrong character as
//decimal seperator (depends on globalization settings)
String.format("{0:0,00000}",f);//comma for decimal
String.format("{0:0.00000}",f);//point for decimal
//how it works: first you say {0} meaning first variable after the text " "
//then you specify the notation :0,00000 meaning 1 number before the seperator at least
// and 5 numbers after.

Example

f = 0,123456789
String.format("Text before the number {0:0.00000} Text after the number",f);
//output:
//Text before the number 0,12345 Text after the number

//input: 123456789.1234
textBox2.Text = string.Format("{0:0,0##E0}", f); 
//output: 1.235E5
0
On

If you want to round in order to use it later in calculations, use Math.Round((decimal)myDouble, 3).

If you don't intend to use it in calculation but need to display it, use double.ToString("F3").