Format a number to two decimal places

前端 未结 2 493
陌清茗
陌清茗 2021-02-12 18:50

Give me a native (no jQuery, Prototype, etc. please) JavaScript function that converts numbers as follows:

input:  0.39, 2.5,  4.25, 5.5,  6.75, 7.75, 8.5
outpu         


        
2条回答
  •  心在旅途
    2021-02-12 19:06

    You can use the toFixed() method on Number objects:

    var array = [0.39, 2.5,  4.25, 5.5,  6.75, 7.75, 8.5], new_array = [];
    for(var i = 0, j = array.length; i < j; i++) {
        if(typeof array[i] !== 'number') continue;
        new_array.push(array[i].toFixed(2));
    }
    

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题