Cognitive Hazard
Cognitive Hazard

Reputation: 1192

print at least one decimal place in c++?

I want to stringify double values in C++ with up to 10 decimal places, so I use something like

std::stringstream s;
double value = 3.1415926;
s << "value is " << std::setprecision(10) << value;

However, if value has some exact integral value such as 4.0, I want it to print 4.0 and not just 4. Is there some way to accomplish this with either C++ stringstream, or even old-school snprintf()?

So far, the only solution I can think of is to compare value to floor(value):

std::stringstream s;
if (floor(value) == value)
  s << std::setprecision(1) << std::fixed << value;
else
  s << std::setprecision(10) << value;

I'll keep that solution if I have to, but I'm curious if I'm overlooking some iostream gadget that could help me avoid the conditional.

Upvotes: 2

Views: 2606

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 598384

Use std::fixed:

s << "value is " << std::fixed << std::setprecision(10) << value;

Live Demo


Update: I think I misread what you are looking for. std::fixed alone doesn't address the issue you are looking to solve - using precision 1 for whole numbers and precision 10 for fractional numbers. You can use std::modf() to differentiate between them (for simplicity, I'll ignore Infinite and NaN, but make sure you account for them in your actual code), eg:

#include <cmath>
std::stringstream s;
double integral;
if (std::modf(value, &integral) == 0)
    s << std::fixed << std::setprecision(1) << integral;
else
    s << std::fixed << std::setprecision(10) << value;

Upvotes: 2

Related Questions