8

I want to ask how to remove trailing zeros after decimal point?

I've read lots of topics about it but I don't understand them clearly. Could you show me any easy understanding ways ?

For example 12.50 to 12.5, but the actual output is 12.50

lenik
  • 23,228
  • 4
  • 34
  • 43
  • 2
    Welcome to Stack Overflow. Please take the time to go through the [The Tour](http://stackoverflow.com/tour) and refer to the material from the [Help Center](http://stackoverflow.com/help/asking) on what and how you can ask here.It's specially important to post a [mcve]. – R Sahu Sep 11 '19 at 05:39
  • I don't think there is a direct way of doing that.. unless the inputs are defined interns of type of data, precision and other parameters which may be parsed to format accordingly – asio_guy Sep 11 '19 at 05:54
  • 1
    Possible duplicate of [Remove trailing zeros](https://stackoverflow.com/questions/4525854/remove-trailing-zeros) – Syntax Hacker Sep 11 '19 at 06:29
  • 3
    @SyntaxHacker This is c++, not c#. – zdf Sep 11 '19 at 06:38
  • So if I understand the question correctly, you have some number that you want to round to 2 decimals after the point and display such than any trailing zeroes are removed. Please, see my answer below. – nielsen Sep 11 '19 at 14:09

6 Answers6

13

This is one thing that IMHO is overly complicated in C++. Anyway, you need to specify the desired format by setting properties on the output stream. For convenience a number of manipulators are defined.

In this case, you need to set fixed representation and set precision to 2 to obtain the rounding to 2 decimals after the point using the corresponding manipulators, see below (notice that setprecisioncauses rounding to the desired precision). The tricky part is then to remove trailing zeroes. As far as I know C++ does not support this out of the box, so you have to do some string manipulation.

To be able to do this, we will first "print" the value to a string and then manipulate that string before printing it:

#include <iostream>
#include <iomanip>

int main()
{ 
    double value = 12.498;
    // Print value to a string
    std::stringstream ss;
    ss << std::fixed << std::setprecision(2) << value;
    std::string str = ss.str();
    // Ensure that there is a decimal point somewhere (there should be)
    if(str.find('.') != std::string::npos)
    {
        // Remove trailing zeroes
        str = str.substr(0, str.find_last_not_of('0')+1);
        // If the decimal point is now the last character, remove that as well
        if(str.find('.') == str.size()-1)
        {
            str = str.substr(0, str.size()-1);
        }
    }
    std::cout << str << std::endl;
}
nielsen
  • 5,641
  • 10
  • 27
1

For C++ check this How to output float to cout without scientific notation or trailing zeros?

using printf() you may use following method to do this,

int main()
{ 
    double value = 12.500;
    printf("%.6g", value );  // 12.5 with 6 digit precision
    printf("%.6g", 32.1234);  // 32.1234
    printf("%.6g", 32.12300000);  // 32.123
}
AshishP
  • 39
  • 6
  • This will work fine but it will fail if value is like ` 12.520400` it should return `12.5204` but it returns '12.52'. which is wrong. – Ankit Mishra Apr 25 '20 at 19:44
1
std::string example = std::to_string(10.500f);   
 while (example[example.size() - 1] == '0' || example[example.size() - 1] == '.')
        example.resize(example.size() - 1);
  • 1
    Although this is what I would have thought of, the solution with `find_last_not_of` is slightly more efficient, as it only does 2 substr() instead of multiple resize(). When counting the changes to the string that's O(2) vs O(n), I think. – Erik Bongers Apr 04 '22 at 20:11
0

Just use 'printf' function. printf("%.8g",8.230400); will print '8.2304'

float value =4.5300; printf ("%.8g",value); will return 4.53.

Try this code . It is quite simple.

Ankit Mishra
  • 530
  • 8
  • 16
0

I was stumped by this for a while and didn't want to convert to a string to get the job done, so I came up with this:

float value = 1.00;
char buffer[10];
sprintf(buffer, "%.2f", value);

int lastZero = strlen(buffer);
for (int i = strlen(buffer) - 1; i >= 0; i--)
{
    if (buffer[i] == '\0' || buffer[i]=='0' || buffer[i]=='.')
        lastZero = i;
    else
        break;
}

if (lastZero==0)
    lastZero++;
char newValue[lastZero + 1];
strncpy(newValue, buffer, lastZero);
newValue[lastZero] = '\0';

newValue = 1

Ricky
  • 1,587
  • 2
  • 12
  • 20
-1

you can round-off the value to 2 digits after decimal,

x = floor((x * 100) + 0.5)/100;

and then print using printf to truncate any trailing zeros..

printf("%g", x);

example:

double x = 25.528;
x = floor((x * 100) + 0.5)/100;
printf("%g", x);

output: 25.53

Harish
  • 41
  • 2
  • It is better and simpler to let `printf` do the rounding by specifying the precision in the format string: `%.2g` (or `%.2f` if you do not want scientific representation). – nielsen Sep 11 '19 at 06:34
  • @ZDF Yes, it works for negative numbers since `floor` always rounds down. You are probably thinking of casting to `int` which does truncation (rounding negative numbers up and positive numbers down). – nielsen Sep 11 '19 at 08:14
  • 1
    This is a C approach that will work in C++. But not really a C++ approach. The question is tagged C++ so one could suppose the desired answer should provide C++ way of doing it... – slepic Sep 11 '19 at 08:30
  • @neilsen, I am not sure if %.2f will round off or will just clip the value after first 2 decimal points. slepic I am not very eager of c vs c++, but would love to hear about why one approach is better vs other. For this case, I think my approach will do the work well and is simple enough to understand. As a bonus, it is more performant than using cout variant. – Harish Sep 13 '19 at 01:16
  • @Harish well being better Is quite vague statement. So Id rather not answer that. Let me just say that OP never asked to output the rounded value to standard output. Which Is what printf does. You might object there Is also fprintf. But It still needs a filé descrptor. In c++ there Is probably some more flexible abstraction... – slepic Sep 23 '19 at 11:01
  • Well I agree this is not pure c++ approach, but using printf with %g is simpler and probably more efficient. And that's what I mean by better. OP asked how to ignore the trailing zeros and that implicitly means he's manipulating the number as string, be it std output, file output, or even string output (sprintf). – Harish Aug 15 '20 at 13:24