Correct Use of Std::Cout.Precision() - Not Printing Trailing Zeros

Correct use of std::cout.precision() - not printing trailing zeros


#include <iostream>
#include <stdlib.h>
#include <iomanip>
int main()
{
int a = 5;
int b = 10;
std::cout << std::fixed;
std::cout << std::setprecision(4);
std::cout << (float)a/(float)b << "\n";
return 0;
}

You need to pass std::fixed manipulator to cout in order to show trailing zeroes.

std::setprecision not showing trailing decimals

To force trailing zeros, use std::fixed:

std::string object = "1";
std::stringstream objectString;
objectString << std::fixed << std::setprecision(8) << atof(object.c_str());
std::cout << "ObjectString=" << objectString.str() << " ";
std::cout << std::fixed << std::setprecision(10) << double(atof(object.c_str())) << "\n";

Output:

ObjectString=1.00000000 1.0000000000

Set Precision and Clip Trailing Zeros but Never Print Exponent

Sadly there is no way to force streams to use printf's %f behavior. So the only way to handle this is trimming decimal places manually as necessary. I've added a C++ code sample that handles this:

string fullfloat(static_cast<size_t>(log10(numeric_limits<declval(input)>::max())) + 5U, '\0'); // Adding 1 for the 10s place, 1 for the '.' 2 for the decimal places, and 1 for the null
const size_t length = size(fullfloat) - sprintf(data(fullfloat), "%.2f", input );

*(--mismatch(rbegin(fullfloat) + length, next(rbegin(fullfloat), 3U + length), "00.").first) = '\0';

fullfloat will now contain the correct string, but because it's size will extend past the applied '\0' character the only way to get it to print property would be to use data():

cout << data(fullfloat);

cout float without trailing zeros and with only 3 digits after the

It looks like you don't want to do any kind of rounding. I think this function will do what you want:

#include <vector>
#include <iostream>
#include <string>

std::string remove_trailing_zeros(float num, int precision)
{
const int maxPrecision(6);
if (precision > maxPrecision) {
throw std::invalid_argument("precision too much for float!");
}

std::string str = std::to_string(num); //convert to string
str.erase(str.find('.') + precision + 1); //chop to precision
str.erase(str.find_last_not_of('0') + 1, std::string::npos ); //erase any trailing zeroes
if (str.back() == '.') //remove remaining dot if necessary
str.pop_back();

return str;
}

int main() {
std::vector<float> numbers = { 0.3, 1, 1.456432, 1.4010006, 1.0 };

for (auto n : numbers) {
std::cout << remove_trailing_zeros(n, 3) << std::endl;
}
}

Output:

0.3
1
1.456
1.401
1

Be careful you don't exceed a precision of 6 for floats because that's the default number of decimal numbers a float converted to string contains.

Dividing an integer with a double

setprecision(n); tells the maximum number n of digits to use, not the minimum. Keep in mind that trailing zeroes are automatically discarded, this is what happens when you divide 3 by 3.0, the result is 1.000... but the zeroes get discarded. If you want to get n digits at all times you have to use std::fixed like this:

cout << fixed;
cout << setprecision(2);

and it will give you 2 digits, so for instance 3 / 3.0 will yield 1.00.

float number leading and trailing zeros format

use std stream formatters from iomanip.
Stop using printf : Why not use printf() in C++

#include <iostream>
#include <iomanip>
#include <vector>


int main()
{
std::vector<double> values{ 0.001, 0.002, 0.2, 1.001, 9.090, 99.100 };

for (const auto value : values)
{
std::cout << std::fixed;
std::cout << std::setprecision(3);
std::cout << std::setfill('0') << std::setw(7);
std::cout << value << std::endl;
}

return 0;
}

Remove trailing zero in C++

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;
}


Related Topics



Leave a reply



Submit