Hello, this is my first post here...please bear with me, I'm an amateur at this...
I want to write a program that can display any nonnegative floating point value as a decimal number with exactly two digits to the right of the decimal, because we are dealing with monetary quantities.
This is pretty straightforward, so I have something to the effect ofThis works in most but not all cases, namely when pay < .01. Even when setprecision is 0 or below it still displays one significant digit (i.e. 0.003). I could get around this by placing a check to display the quantity as 0.00 when precision < 1, I suppose, but then a quantity like 0.009 won't be rounded up to 0.01. Maybe multiply by 100 and round to the nearest integer, then divide by 100 again?Code:float pay; int precision; int main() { ... cout<<"Enter the pay\n"; cin>>pay; precision=floor(log10(pay))+3; cout<<setprecision(precision)<<"\n\nThe pay is "<<pay<<"\n" ... }
As well, when an integer quantity like 123 is inputted, it is redisplayed as an integer though the value for setprecision will be what I want it to be (5 in this case). I could tack on ".00" when pay is an integer, but that doesn't account for situations where 123.006 can be displayed as 123.01 but 123.004 -- a non integer value -- will be regurgitated as simply 123. Maybe I should follow my own suggestion again, multiply/round/divide with 100.
I have a feeling I'm making this a lot harder than it needs to be or missing something obvious. Maybe I should forgo setprecision altogether, and display the integer quantity and then calculate/display the rounded quantity to the right of the decimal.
Oh well, even if no one responds to this thread, typing it out helped me think the problem through