#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.";
7 Years
Discussion Span
Last Post by MosaicFuneral

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.


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;

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.


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);

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.