I would like to format my numbers to always display 2 decimal places, rounding where applicable.
Examples:
number display
------ -------
1
I had to decide between the parseFloat() and Number() conversions before I could make toFixed() call. Here's an example of a number formatting post-capturing user input.
HTML:
Event handler:
$('.dec-number').on('change', function () {
const value = $(this).val();
$(this).val(value.toFixed(2));
});
The above code will result in TypeError exception. Note that although the html input type is "number", the user input is actually a "string" data type. However, toFixed() function may only be invoked on an object that is a Number.
My final code would look as follows:
$('.dec-number').on('change', function () {
const value = Number($(this).val());
$(this).val(value.toFixed(2));
});
The reason I favor to cast with Number() vs. parseFloat() is because I don't have to perform an extra validation neither for an empty input string, nor NaN value. The Number() function would automatically handle an empty string and covert it to zero.