Add .00 (toFixed) only if number has less than two decimal places

前端 未结 6 1889
無奈伤痛
無奈伤痛 2020-12-29 20:47

I need to add zeroes, so that each number has at least two decimals, but without rounding. So for example:

5      --> 5.00
5.1    --> 5.10
5.11   --&g         


        
相关标签:
6条回答
  • 2020-12-29 20:56

    Here you go:

    function addZeroes(num) {
    // Convert input string to a number and store as a variable.
        var value = Number(num);      
    // Split the input string into two arrays containing integers/decimals
        var res = num.split(".");     
    // If there is no decimal point or only one decimal place found.
        if(res.length == 1 || res[1].length < 3) { 
    // Set the number to two decimal places
            value = value.toFixed(2);
        }
    // Return updated or original number.
    return value;
    }
    
    // If you require the number as a string simply cast back as so
    var num = String(value);
    

    See updated fiddle for demonstration.


    edit: Since I first answered this, javascript and I have progressed, here is an updated solution using es6, but following the same idea:

    function addZeroes(num) {
      const dec = num.split('.')[1]
      const len = dec && dec.length > 2 ? dec.length : 2
      return Number(num).toFixed(len)
    }
    

    Updated fiddle

    0 讨论(0)
  • 2020-12-29 21:02

    Here is a function that will do this, function expects a number

    var addZeroes = function(num) {
      var numberAsString = num.toString();
    
      if(numberAsString.indexOf('.') === -1) {
        num = num.toFixed(2);
        numberAsString = num.toString();
      } else if (numberAsString.split(".")[1].length < 3) {
        num = num.toFixed(2);
        numberAsString = num.toString();
      }
    
      return numberAsString
    };
    
    0 讨论(0)
  • 2020-12-29 21:04

    decimalNumber = number => Number.isInteger(number) ? number.toFixed(2) : number

    0 讨论(0)
  • 2020-12-29 21:07

    The below code provides one way to do what you want. There are others.

    function addZeroes(num) {
        // Cast as number
        var num = Number(num);
        // If not a number, return 0
        if (isNaN(num)) {
            return 0;
        }
        // If there is no decimal, or the decimal is less than 2 digits, toFixed
        if (String(num).split(".").length < 2 || String(num).split(".")[1].length<=2 ){
            num = num.toFixed(2);
        }
        // Return the number
        return num;
    }
    
    console.log(addZeroes(5)); // Alerts 5.00
    console.log(addZeroes(5.1)); // Alerts 5.10
    console.log(addZeroes(5.11)); // Alerts 5.11
    console.log(addZeroes(5.111)); // Alerts 5.111
    

    http://jsfiddle.net/nzK4n/

    0 讨论(0)
  • 2020-12-29 21:15

    For number type textbox

    Append .00 if number present

    function addZeroes(ev) {
        debugger;
        // Convert input string to a number and store as a variable.
        var value = Number(ev.value);
        // Split the input string into two arrays containing integers/decimals
        var res = ev.value.split(".");
        // If there is no decimal point or only one decimal place found.
        if (res.length == 1 || res[1].length < 3) {
            // Set the number to two decimal places
            value = value.toFixed(2);
        }
        // Return updated or original number.
        if (ev.value != "") {
            ev.value = String(value);
        }
    }
    <input type="number" step=".01" onchange="addZeroes(this)" />

    0 讨论(0)
  • 2020-12-29 21:22

    Maybe use .toLocaleString():

    var num = 5.1;    
    var numWithZeroes = num.toLocaleString("en",{useGrouping: false,minimumFractionDigits: 2});
    console.log(numWithZeroes);
    

    As a function/demo:

    function addZeroes(num) {
       return num.toLocaleString("en", {useGrouping: false, minimumFractionDigits: 2})
    }
    
    console.log('before   after       correct');
    console.log('5      ->', addZeroes(5) , '  --> 5.00');
    console.log('5.1    ->', addZeroes(5.1) , '  --> 5.10');
    console.log('5.11   ->', addZeroes(5.11) , '  --> 5.11 (no change)');
    console.log('5.111  ->', addZeroes(5.111) , ' --> 5.111 (no change)');
    console.log('5.1111 ->', addZeroes(5.1111) , '--> 5.1111 (no change)');
    console.log('-5     ->', addZeroes(-5) , ' --> -5.00');

    And if you must use .toFixed(), here's a one-liner:

    var num = 5.1;    
    var numWithZeroes = num.toFixed(Math.max(((num+'').split(".")[1]||"").length, 2));
    console.log(numWithZeroes);
    

    Or, again, as a function/demo:

    function addZeroes(num) {
       return num.toFixed(Math.max(((num+'').split(".")[1]||"").length, 2));
    }
    
    console.log('before   after       correct');
    console.log('5      ->', addZeroes(5) , '  --> 5.00');
    console.log('5.1    ->', addZeroes(5.1) , '  --> 5.10');
    console.log('5.11   ->', addZeroes(5.11) , '  --> 5.11 (no change)');
    console.log('5.111  ->', addZeroes(5.111) , ' --> 5.111 (no change)');
    console.log('5.1111 ->', addZeroes(5.1111) , '--> 5.1111 (no change)');
    console.log('-5     ->', addZeroes(-5) , ' --> -5.00');

    0 讨论(0)
提交回复
热议问题