ANS-1343 · SUITESCRIPT DEVELOPMENT
How to Round Floating-Point Numbers in NetSuite JavaScript
This guide provides a simple JavaScript function to accurately round decimal values to a specified number of decimal places within NetSuite scripts.
Short answer
To round floating-point numbers in NetSuite JavaScript, use a custom function that multiplies the number by a power of 10, rounds it, and then divides by the same power of 10. This method ensures precise rounding to a specified number of decimal places, as demonstrated by the `roundNumber` function.
Scenario
NetSuite users often encounter scenarios where precise rounding of floating-point numbers is required in custom scripts or calculations. Standard JavaScript rounding functions may not always provide the desired control over the number of decimal places, leading to potential inaccuracies in financial or quantitative data.
Solution
To achieve precise rounding of floating-point numbers to a specified number of decimal places in NetSuite JavaScript, implement the following custom function:
function roundNumber(num, dec) { var resultMath.round(num*Math.pow(10,dec))/Math.pow(10,dec); return result; }This function takes two arguments: num (the number to be rounded) and dec (the desired number of decimal places). The function multiplies the number by 10 raised to the power of dec, rounds the result to the nearest whole number, and then divides by the same power of 10.For example, using this function yields the following results:
roundNumber(3.6682, 2) returns 3.67roundNumber(3.6622, 2) returns 3.66roundNumber(3.66229, 4) returns 3.6623Expert NetSuite Support
Need help with this NetSuite issue?
SuiteScript Development consulting and configuration support
