very generic questions about setprecision

Hi, I've tried looking this up but couldn't find an answer to my question, and decided to post a thread asking for help. So I've tried using something like

 
cout << setprecision(2) << price;


and it works perfectly. Instead of displaying "14.5896532" from calculation, it will only display "14.58" which is exactly what I want. However, I noticed that whenever I use "fixed setprecision" on part of the code, everything goes to having 2 decimal places, and I don't want that. For example, other than this part, I want the user to be able to enter a number and display exactly what they enter unless it goes beyond 2 decimal points.

When the user inputs "14", it should display "14", not "14.00";
when the user inputs "14.5", it should display "14.5", not "14.50";
when the user inputs "14.5236581", it should display "14.52".
when the user inputs "14.5256581", it should display "14.53"

So basically, I want in one section, the number displays do exactly what "fix setprecisions(2)", and on the other part(s), the number displays exactly what the user types in, be it integer or decimal, unless it has over 2 decimals then round off to 2 decimals. Can anyone give an example on how this can be accomplished? Thanks in advance.
cout << setprecision(2) << price;
and it works perfectly. Instead of displaying "14.5896532" from calculation, it will only display "14.58" which is exactly what I want.


Actually, this will produce the output "14" unless the output stream's fixed flag was previously set. precision refers to the number of significant digits to display, except when fixed is used, where it then refers to the number of digits after the decimal to display.

To achieve what you want, convert your doubles to strings and modify the strings to meet your arbitrary format requirements.
Alternatively, you could check out std::modf, which might be what you're looking for.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <cmath>
#include <iomanip>

int main ()
{
    double values[] = { 14,  14.5,  14.5236581, 14.5256581, -14, -14.5, -14.5236,   -14.5256 } ;

    for( double v : values )
    {
        bool negative = v < 0 ;
        if(negative) { v = -v ; std::cout << '-' ; }

        long long i = std::llround( v * 100 ) ;
        long long a = i / 100 ;
        long long b = i % 100 ;

        std::cout << a ;
        if(b) std::cout << '.' << ( b%10 ? b : b/10 )  ;
        std::cout << ' ' ;
    }
    std::cout << '\n' ;
}

http://coliru.stacked-crooked.com/a/3c1f6f30c86cfc83
Topic archived. No new replies allowed.