chop unused decimals with javascript

前端 未结 7 1042
鱼传尺愫
鱼传尺愫 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:31
    String(4) // "4"
    String(4.1) // "4.1"
    String(4.10) // "4.1"
    String(4.01) // "4.01"
    

    parseFloat works, but you've got to cast it back to a string.

    0 讨论(0)
  • 2021-02-13 14:33
    string to string: parseFloat(value).toFixed(2);
    string to number: +(parseFloat(value).toFixed(2))
    number to number: Math.round(value*100)/100;
    number to string: (Math.round(value*100)/100).toFixed(2);
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-13 14:38

    I think this is what you want

        v = 33.404034
        v.toFixed(2) # v -> 33.40
        parseFloat(v.toFixed(2)) # 33.4
    

    and you have

        v = 33.00704034
        v.toFixed(2) # v -> 33.01
        parseFloat(v.toFixed(2)) # 33.01
    
        v = 33.00304034
        v.toFixed(2) # v -> 33.00
        parseFloat(v.toFixed(2)) # 33
    
    0 讨论(0)
  • 2021-02-13 14:38

    I am trying to find a solution like that right now. This is how I got here.

    I used Number() function for my application, but looks like it's working the same as parseFloat()

    http://jsfiddle.net/4WN5y/

    I remove and commas before checking the number.

     var valueAsNumber = Number( val.replace(/\,/g,'') );
    
    0 讨论(0)
  • 2021-02-13 14:39

    Your code also chops off zeros in numbers like "1000". A better variant would be to only chop of zeros that are after a decimal point. The basic replacement with regular expressions would look like this:

    str.replace(/(\.[0-9]*?)0+$/, "$1"); // remove trailing zeros
    str.replace(/\.$/, "");              // remove trailing dot
    
    0 讨论(0)
提交回复
热议问题