views:

360

answers:

2

How would you implement a ROUND function:

ROUND(value, number of digits)
pi=3.14159265358979323
so, for example, ROUND(pi, 3) = 3.142

if you had these functions at your disposal:
AINT - truncates a value to a whole number
ANINT - calculates the nearest whole number
NINT - returns the nearest integer to the argument

or never minding the above functions, how is floating ROUND done at all ?

+1  A: 

I would assume, excuse my pseudo-code

function Round(value, num){
    numsToSave = POWER(10, num);
    value *= numsToSave ; //Get the numbers we don't want rounded on the left side of the floating point
    value = AINT( ANINT(value) );
    value /= numsToSave;

    return value;
}

or

function Round(value, num){
    numsToSave = POWER(10, num);
    value *= numsToSave ; //Get the numbers we don't want rounded on the left side of the floating point
    value = NINT(value);
    value /= numsToSave;

    return value;
}
Dmitri Farkov
I presume you meant power instead of multiplication in the first line of your function.
David Hanak
Yeah, didn't realize the math... Gimme my morning coffee :p
Dmitri Farkov
+4  A: 

If you don't need to worry about overflow, here's how:

ROUND(value, nod) = NINT(value * POWER(10, nod)) / POWER(10, nod)

Otherwise you need to take care of the integer part and the float part separately.

David Hanak
-1 You always need to worry about overflow.
Oorang
@Oorang: In case of a generic ROUND() function, definitely. If you are application specific, you could, for example, know in advance that both value and nod are below certain thresholds, which will guarantee that the above formula does not overflow.
David Hanak