Search code examples
c++floating-pointtruncate

Remove trailling zeros from a number in C++


Example of values I am getting

 12.230030
 4.000000
 400.402100
 132.000000
 53.120203
 100.0010
 45.320030

I want this floating values to print like this

12.230030
4
400.4021
132
53.120203
100.001
45.32003

Solution

  • Simply use printf function.

    float val=12.02300;
    printf("%.8g",val);
    

    Will give correct output. In this case it will output as 12.023
    example of other output For value=400.00; it will output 400
    For value=32.122300 it will output 32.1223 .