Allir
Allir

Reputation: 1

I need to know how to round numbers to a certain decimal place in C++

I Have this code to find out the total purchase price of some numbers and i need to know how to round the numbers to only 2 decimal places.

#include <iostream.h>
#include <cstdlib.h>
#include <string.h>

int main() {
    float sale_price;
    float tax_rate;
    float discount_rate;

    system("cls");
    system("color 07");
    cout << "\n\nWelcome to the second version of my total purchase price calculator!\n";
    cout << "How much did your recently purchased item cost? ";
    cin >> sale_price;
    cout << "What is the tax rate in your area? ";
    cin >> tax_rate;
    cout << "What was the discount rate, if any (if none, just put down 1) ";
    cin >> discount_rate;
    float tax = sale_price*(tax_rate/100);
    float discount = sale_price*(discount_rate/100);
    float total_price = sale_price + tax - discount;
    cout << "The total price of your item is $"<<total_price<<" with $"<<tax<<" tax minus $"<<discount<<" due to discount.\n";
    cout << "Would you like a reciept? y or n. ";
    string answer;
    End:
    cin >> answer;
    if (answer == "y") {
        goto Reciept;
    }
    else if (answer == "n") {
        return 0;
    }
    else {
        cout << "Try another answer\n";
        goto End;
    }
    Reciept:
    system("cls");
    system("color 70");
    cout << "\xda\xc4\xc4\xc4\xc4\xc4\xc4\xc4\xc4\\xc4\xc4\xc4\xc4\xc4\xc4\xc4\xc4\xbf\n";
}

this usually gives me 4 decimal places just FYI

Upvotes: 0

Views: 479

Answers (5)

Dabbler
Dabbler

Reputation: 9873

Round to 2 decimals: int((n * 100.0) + 0.5) / 100;
Round to 3 decimals: int((n * 1000.0) + 0.5) / 1000;
etc.

Upvotes: 3

marcocamejo
marcocamejo

Reputation: 828

You should use Iomanip's setprecision:

setprecision reference

Upvotes: 2

David Hammen
David Hammen

Reputation: 33126

The easy way is to use setprecision:

 std::cout << "The total price of your item is $"
           << std::setprecision(2) << total_price ...

This will occasionally get things wrong. A better solution is to use an improved rounding function that is not a part of the standard (e.g., How does Excel successfully Rounds Floating numbers even though they are imprecise?). An even better solution is to implement your own fixed point arithmetic algorithm so as to avoid this problem entirely. You can still go one better than that: Use a fixed point arithmetic package that someone else has already written and tested to the nth degree.

Upvotes: 2

kralyk
kralyk

Reputation: 4397

Do

cout.precision(2);
cout << fixed;

before you output the floats.

Upvotes: 1

Chriszuma
Chriszuma

Reputation: 4568

When you output with cout, use the setprecision() operator.

cout << fixed;
cout << setprecision(2) << sale_price*(tax_rate/100);

Upvotes: 1

Related Questions