How to parse float with two decimal places in javascript?

前端 未结 16 1608
春和景丽
春和景丽 2020-11-27 08:55

I have the following code. I would like to have it such that if price_result equals an integer, let\'s say 10, then I would like to add two decimal places. So 10 would be 10

相关标签:
16条回答
  • 2020-11-27 09:35

    Simple JavaScript, string to float:

    var it_price = chief_double($("#ContentPlaceHolder1_txt_it_price").val());
    
    function chief_double(num){
        var n = parseFloat(num);
        if (isNaN(n)) {
            return "0";
        }
        else {
            return parseFloat(num);
        }
    }
    
    0 讨论(0)
  • 2020-11-27 09:36

    @sd Short Answer: There is no way in JS to have Number datatype value with trailing zeros after a decimal.

    Long Answer: Its the property of toFixed or toPrecision function of JavaScript, to return the String. The reason for this is that the Number datatype cannot have value like a = 2.00, it will always remove the trailing zeros after the decimal, This is the inbuilt property of Number Datatype. So to achieve the above in JS we have 2 options

    1. Either use data as a string or
    2. Agree to have truncated value with case '0' at the end ex 2.50 -> 2.5.
    0 讨论(0)
  • 2020-11-27 09:37

    If your objective is to parse, and your input might be a literal, then you'd expect a float and toFixed won't provide that, so here are two simple functions to provide this:

    function parseFloat2Decimals(value) {
        return parseFloat(parseFloat(value).toFixed(2));
    }
    
    function parseFloat2Decimals(value,decimalPlaces) {
        return parseFloat(parseFloat(value).toFixed(decimalPlaces));
    }
    
    0 讨论(0)
  • 2020-11-27 09:38

    When you use toFixed, it always returns the value as a string. This sometimes complicates the code. To avoid that, you can make an alternative method for Number.

    Number.prototype.round = function(p) {
      p = p || 10;
      return parseFloat( this.toFixed(p) );
    };
    

    and use:

    var n = 22 / 7; // 3.142857142857143
    n.round(3); // 3.143
    

    or simply:

    (22/7).round(3); // 3.143
    
    0 讨论(0)
  • 2020-11-27 09:38

    Please use below function if you don't want to round off.

    function ConvertToDecimal(num) {
        num = num.toString(); //If it's not already a String
        num = num.slice(0, (num.indexOf(".")) + 3); //With 3 exposing the hundredths place
       alert('M : ' +  Number(num)); //If you need it back as a Number    
    }
    
    0 讨论(0)
  • 2020-11-27 09:40

    To return a number, add another layer of parentheses. Keeps it clean.

    var twoPlacedFloat = parseFloat((10.02745).toFixed(2));
    
    0 讨论(0)
提交回复
热议问题