Round double to N decimal places.

MosaicFuneral 0 Tallied Votes 9K Views Share

Got bored, remember a question asked in the forums, and decided to try something similar.

#include <iostream>
#include <cmath>
#include <stdint.h>
using namespace std;

void round_nplaces(double &value, const uint32_t &to)
{
    uint32_t places = 1, whole = *(&value);
    for(uint32_t i = 0; i < to; i++) places *= 10;

    value -= whole; //leave decimals

    value *= places;  //0.1234 -> 123.4
    value  = round(value);//123.4 -> 123
    value /= places;  //123 -> .123

    value += whole; //bring the whole value back
}

int main()
{
    double x[5] = { 5.3456, 3.12345, 999.892903, 0.456, 0.5678901 };

    for(int i = 0; i < 5; i++)
    {
      cout << x[i] << " rounded to 3rd decimal is ";
      round_nplaces(x[i], 3); //change it to whatever you want
      cout << x[i] << endl;
    }

    cout << endl << "Press Return.";
    cin.get();
    return(0);
}
thoughtcoder 167 Junior Poster

Why aren't you using the signature double round_nplaces(double value, uint32_t to) ?

Passing primitive types by reference is useless unless you want multiple return values.

Also, you don't need to separate the value out into whole number / fractional part.

Also your code doesn't even compile.

thoughtcoder 167 Junior Poster

Here is a simpler implementation, but without the fun of computing the to'th power of 10.

double round_nplaces(double value, int to)
{
    double places = pow(10.0, to);
    return round(value * places) / places;
}
MosaicFuneral 812 Nearly a Posting Virtuoso

It's a habit from passing larger container objects, and pow() just takes the fun out of even bothering to click on the editor.

Compiles fine in MinGW. The fist thing that comes to mind, when you say it's not compiling, is that you're using an older compiler that doesn't have stdint.h; or it's not letting you compile with warnings, in this case the double to unsigned int casting.

Samran 0 Newbie Poster

Why dont you do rounding in this way...

#include <iomanip>

cout << fixed << setprecision (n) << xyz << endl;

where n is an integer, the decimal places and xyz is a type double variable.

After you are done, end the fixed manipulation with

cout.unsetf (ios::fixed);

MosaicFuneral 812 Nearly a Posting Virtuoso

That would never cure my boredom either.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.