Rounding a price to 2 decimal figures???

Hi all,

I have been learning C++ over the course of the last few weeks. One task I have been assigned is to make a VAT calculator. I'm not interested in how VAT works, just this:

How do I round the price of something to 2 decimal places? For example you cannot have a keyboard worth 5.99999 dollars, instead it is rounded to 5.99 or 6.

Any help will be appreciated.

Cheers

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
using namespace std;

void calculateVat()
{
    float price;
    float vat;

    cout<<"What is the price of the item?"<<endl;
    cin>>price;
    cout<<"What is the VAT rate? (%)"<<endl;
    cin>>vat;

    vat = (1+(vat/100))*price;

    cout<<"The VAT payable is:  "<<vat<<" pounds"<<endl;
}



int main()
{
    calculateVat();
}
Quickest way is probably using the precision member function or io manipulator for your output stream. Look up manipulator <iomanip>.

Keeping a number as a float will always leave it prone to floating-point accuracy issues.

Alternatively, you could multiply by 100 and find the nearest integer to find the price in cents or pence. The number of cents or pence could be separated from the number of dollars or pounds by modulo 100; the remainder, once integer-divided by 100 gives number of dollars or pounds.
Topic archived. No new replies allowed.