A common web page task is to round a numeric value to a specified number of decimal places. JavaScript’s Math
object offers several rounding functions that can help, but if you want to perform the most common rounding task—rounding a floating-point number to a specified number of decimals, padded with zeroes, if necessary—then you need to do a bit more work. Specifically, you need to round the value using the toFixed()
function, but before you can apply that function you need to check whether the value is a string (as it would be, for example, if it came from an input
field) and, if so, convert it to a number. Let’s see how it works:
Let’s take a look at how the JavaScript works:
var roundDecimals
{…
function(originalNumber, decimals)
{…
originalNumber
: The value you want rounded.decimals
: The number of decimal places you want in the rounded value.
var unroundedFloat = originalValue
unroundedFloat
variable.
if (typeof originalValue === 'string')
typeof
to check whether the data type of the passed value is a string.
unroundedFloat = parseFloat(originalValue)
parseFloat()
to convert it to a floating-point number.
return unroundedFloat.toFixed(decimals)
etc.
toFixed()
, and then return the rounded value.
$('#rounding-decimals-button').click…
roundDecimals()
function.
If you’re working on a small project where loading the jQuery library is overkill, here’s the plain vanilla JavaScript version of the script: