Got bored, remember a question asked in the forums, and decided to try something similar.
Round double to N decimal places.
#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
thoughtcoder 167 Junior Poster
MosaicFuneral 812 Nearly a Posting Virtuoso
Samran 0 Newbie Poster
MosaicFuneral 812 Nearly a Posting Virtuoso
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.