Format a number to two decimal places

前端 未结 2 494
陌清茗
陌清茗 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));
    }
    
    0 讨论(0)
  • 2021-02-12 19:12
    input = 0.3;
    output = input.toFixed(2);
    //output: 0.30
    
    0 讨论(0)
提交回复
热议问题