Format number to always show 2 decimal places

前端 未结 30 2696
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-21 08:17

I would like to format my numbers to always display 2 decimal places, rounding where applicable.

Examples:

number     display
------     -------
1            


        
30条回答
  •  有刺的猬
    2020-11-21 08:38

    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.

提交回复
热议问题