convert a JavaScript string variable to decimal/money

后端 未结 7 1176
盖世英雄少女心
盖世英雄少女心 2020-12-07 14:05

How can we convert a JavaScript string variable to decimal?

Is there a function such as:

parseInt(document.getElementById(amtid4).innerHTML)
         


        
相关标签:
7条回答
  • 2020-12-07 14:09

    An easy short hand way would be to use +x It keeps the sign intact as well as the decimal numbers. The other alternative is to use parseFloat(x). Difference between parseFloat(x) and +x is for a blank string +x returns 0 where as parseFloat(x) returns NaN.

    0 讨论(0)
  • 2020-12-07 14:11

    This works:

    var num = parseFloat(document.getElementById(amtid4).innerHTML, 10).toFixed(2);
    
    0 讨论(0)
  • 2020-12-07 14:14

    Yes -- parseFloat.

    parseFloat(document.getElementById(amtid4).innerHTML);
    

    For formatting numbers, use toFixed:

    var num = parseFloat(document.getElementById(amtid4).innerHTML).toFixed(2);
    

    num is now a string with the number formatted with two decimal places.

    0 讨论(0)
  • 2020-12-07 14:17

    It is fairly risky to rely on javascript functions to compare and play with numbers. In javascript (0.1+0.2 == 0.3) will return false due to rounding errors. Use the math.js library.

    0 讨论(0)
  • 2020-12-07 14:20

    You can also use the Number constructor/function (no need for a radix and usable for both integers and floats):

    Number('09'); /=> 9
    Number('09.0987'); /=> 9.0987
    

    Alternatively like Andy E said in the comments you can use + for conversion

    +'09'; /=> 9
    +'09.0987'; /=> 9.0987
    
    0 讨论(0)
  • 2020-12-07 14:23

    I made a little helper function to do this and catch all malformed data

    function convertToPounds(str) { 
        var n = Number.parseFloat(str);
        if(!str || isNaN(n) || n < 0) return 0;
        return n.toFixed(2);
    }
    

    Demo is here

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