chop unused decimals with javascript

前端 未结 7 1046
鱼传尺愫
鱼传尺愫 2021-02-13 14:27

I\'ve got a currency input and need to return only significant digits. The input always has two decimal places, so:

4.00  ->  4
4.10  ->  4.1
4.01  ->           


        
7条回答
  •  走了就别回头了
    2021-02-13 14:37

    So you're starting with a string and you want a string result, is that right?

    val = "" + parseFloat(val);
    

    That should work. The more terse

    val = "" + +val;
    

    or

    val = +val + "";
    

    would work as well, but that form is too hard to understand.

    How do these work? They convert the string to a number then back to a string. You may not want to use these, but knowing how the JavaScript conversions work will help you debug whatever you do come up with.

提交回复
热议问题