WebDev Workshop logo

WebDev Workshop

tools, code, and books to take your web development skills to the next level

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:

Lines 5-18:
var roundDecimals {…
Defines the function expression that we’ll use to round the number.
Line 5:
function(originalNumber, decimals) {…
Defines the function arguments:
  • originalNumber: The value you want rounded.
  • decimals: The number of decimal places you want in the rounded value.
Line 8:
var unroundedFloat = originalValue
The function assumes the passed value is a true number, so it stores the passed value in the unroundedFloat variable.
Line 11:
if (typeof originalValue === 'string')
The function uses typeof to check whether the data type of the passed value is a string.
Line 14:
unroundedFloat = parseFloat(originalValue)
If the passed value is a string, then use parseFloat() to convert it to a floating-point number.
Line 17:
return unroundedFloat.toFixed(decimals) etc.
Round the numeric value using toFixed(), and then return the rounded value.
Lines 23-49:
$('#rounding-decimals-button').click…
jQuery click handler for the Round It button, which gathers the value to be rounded and the number of decimals and passes these to the 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:

Text is Copyright Logophilia Limited.
Code is licensed under a  Creative Commons Attribution 4.0 International License.
Hand-crafted by Paul McFedries.