0 Replies - 2193 Views - Last Post: 09 July 2012 - 05:24 PM Rate Topic: -----

#1 atraub   User is offline

  • Pythoneer
  • member icon

Reputation: 833
  • View blog
  • Posts: 2,257
  • Joined: 23-December 08

Round number to n decimal places

Posted 09 July 2012 - 05:24 PM

Description: Given a double "a", and an integer "n", this function will round the double to n decimal places. This solution is not optimal, but it does what it needs to do.
#include <math.h>

//double a - number to round
//int n - number of decimal places to round to
double nDecimalPlaces(double a, int n)
{
	return round(a*pow(10,n))/pow(10,n);
}

Is This A Good Question/Topic? 0
  • +

Replies To: Round number to n decimal places

#2 atraub   User is offline

  • Pythoneer
  • member icon

Reputation: 833
  • View blog
  • Posts: 2,257
  • Joined: 23-December 08

Re: Round number to n decimal places

Posted 09 July 2012 - 05:24 PM

Description: Given a double "a", and an integer "n", this function will round the double to n decimal places. This solution is not optimal, but it does what it needs to do.
#include <math.h>

//double a - number to round
//int n - number of decimal places to round to
double nDecimalPlaces(double a, int n)
{
    double pow10 = pow(10,n);
    return round(a*pow10)/pow10;
}


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1