Round a decimal number

mjocasio23
Tera Expert

I having a problem rounding a number to a certain precision ....

I gettting a value as a string from a form field , then I convert that number to a foat and then applied the round function.... but it does not work as I want it...

var temp   = parseFloat(g_form.getValue('substance_allowance'));

temp = Math.round(temp).toFixed(2); it wont work to rund the value two decimals places if a situation applies.... what it does           it rounds up but it moves the decimals two places to the right.

8 REPLIES 8

Greg42
Mega Guru

Hi Michael,



Try this:



function round (value, digits){


    return (Math.round((value*Math.pow(10,digits)).toFixed(digits-1))/Math.pow(10,digits)).toFixed(digits);


}



You can pass a number or a string and provide a number of digits you want to round your result to.




Regards



Greg


This what I get when I feed with 150.256897 = 1.5026 inconsistent with documentation.


Hi Michael,



Not sure why you have such results. How do you call the function?



Tests/results:



round(150.256897, 6) / "150.256897"


round(150.256897, 5) / "150.25690"


round(150.256897, 4) / "150.2569"


round(150.256897, 3) / "150.257"


round(150.256897, 2) / "150.26"


round(150.256897, 1) / "150.3"



Looks pretty consistent to me.




Regards




Greg


mjocasio23
Tera Expert

The only way I got this working was with a converting the value to exponential number...ok I was using round().toFixed(2)...... I did not know the round command contains a second parameter for the decimal places.....


thanks