Formatting a number with exactly two decimals in JavaScript

后端 未结 30 2244
广开言路
广开言路 2020-11-21 06:29

I have this line of code which rounds my numbers to two decimal places. But I get numbers like this: 10.8, 2.4, etc. These are not my idea of two decimal places so how I can

30条回答
  •  孤独总比滥情好
    2020-11-21 06:46

    parse = function (data) {
           data = Math.round(data*Math.pow(10,2))/Math.pow(10,2);
           if (data != null) {
                var lastone = data.toString().split('').pop();
                if (lastone != '.') {
                     data = parseFloat(data);
                }
           }
           return data;
      };
    
    $('#result').html(parse(200)); // output 200
    $('#result1').html(parse(200.1)); // output 200.1
    $('#result2').html(parse(200.10)); // output 200.1
    $('#result3').html(parse(200.109)); // output 200.11
    
    

提交回复
热议问题