2

I am trying to convert a double to string in c++. I would like to format it using a certain minimum amount of significant digits, taking into account machine epsilon.

As an example for 2 minimum significant decimals:

4 -> "4.00"

4.4 -> "4.40"

4.56434444 -> "4.56434444"

I would ideally like to imbue a stream with a locale and a numpunct facet

I currently am using something like

if(abs(floor((m_mes * 100) + 0.5) - (m_mes * 100)) > (std::numeric_limits<double>::epsilon() * 10000))
    buffer << fixed << m_mes;
else
    buffer << fixed << setprecision(2) << m_mes;

EDIT: The absolute value and rounding are a result of compensating for epsilon. The basic idea here is get floor(num * 100), subtract it from (num * 100). If the difference is not zero, then I use a precision higher than 2.

since my minimum significant digits is 2 I didn't want to slow the algorithm down to accept a variable amount.

Is there a way to do this with a numpunct facet? I am new to locales and have little experience with them. Or just a more simple way to accomplish what I have?

jimmyjambles
  • 1,631
  • 2
  • 20
  • 34
  • I think your question makes no sense. How is `4.0` different from `4.000`, and how will you distinguish them? – Kerrek SB Jul 30 '12 at 04:48
  • @KerrekSB I think what he wants is a minimum precision of 2 but there should be no maximum. – Caesar Jul 30 '12 at 04:54
  • @Caesar: Again, this makes no sense. What if I actually have significant digits that happen to be zero? – Kerrek SB Jul 30 '12 at 04:54
  • @KerrekSB I don't think he would then complain as the work is done. – Caesar Jul 30 '12 at 04:57
  • @Caesar You are right, I would not. I am using this to output this already calculated data to the user – jimmyjambles Jul 30 '12 at 05:13
  • @KerrekSB Please see my edited explanation of the algorithm – jimmyjambles Jul 30 '12 at 05:21
  • take a look at [this](http://stackoverflow.com/questions/4217510/how-to-cout-the-correct-number-of-decimal-places-of-a-double-value) and [cppref](http://www.cplusplus.com/reference/iostream/ios_base/precision/) – gda2004 Sep 28 '12 at 15:17

0 Answers0