Round a decimal number
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
11-17-2017 03:19 PM
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.
- Labels:
-
Scripting and Coding
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
11-17-2017 03:47 PM
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
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
11-17-2017 08:25 PM
This what I get when I feed with 150.256897 = 1.5026 inconsistent with documentation.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
11-18-2017 07:24 AM
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
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
11-18-2017 10:04 AM
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