I've got a function that I am using to round a double to a specific decimal place (example: rounding 123.3456 to 123.3) but isn't working correctly.
Below is some test code I wrote. Both functions dround_a() and dround_b() should be exactly the same except dround_b() has the call to round() separated on its own line.
When the code is run, dround_a() returns 123.00, while dround_b() returns 123.30 - which is correct.
Is this a compiler bug causing dround_a not to work correctly, or is it something else?
I'm using the Maple IDE v0.0.12 with a rev.5 Maple board.
Here is the test code:
#include <math.h>
/**
* Rounds a number to a specified number of decimal places
*
* @param num The number to round
* @param ndigits The number of decimal places to round to
*
* @return the rounded value
*/
double dround_a(double num, unsigned int ndigits) {
int a = pow(10, ndigits);
double b = floor(num);
double c = round((num - b) * a) / a;
double x = b + c;
return x;
}
double dround_b(double num, unsigned int ndigits) {
int a = pow(10, ndigits);
double b = floor(num);
double temp = round((num - b) * a);
double c = temp / a;
double x = b + c;
return x;
}
void setup(void) {
}
void loop(void) {
double value = 123.3456;
if (SerialUSB.available()) {
uint8 input = SerialUSB.read();
switch(input) {
case 'a':
SerialUSB.println(dround_a(value, 1));
break;
case 'b':
SerialUSB.println(dround_b(value, 1));
break;
default:
break;
}
SerialUSB.print("> ");
}
}