How to parse float with two decimal places in javascript?

前端 未结 16 1609
春和景丽
春和景丽 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:40

    I have tried this for my case and it'll work fine.

    var multiplied_value = parseFloat(given_quantity*given_price).toFixed(3);
    

    Sample output:

    9.007

    0 讨论(0)
  • 2020-11-27 09:44

    The solution that work for me is the following

    parseFloat(value)
    
    0 讨论(0)
  • 2020-11-27 09:49

    For what its worth: A decimal number, is a decimal number, you either round it to some other value or not. Internally, it will approximate a decimal fraction according to the rule of floating point arthmetic and handling. It stays a decimal number (floating point, in JS a double) internally, no matter how you many digits you want to display it with.

    To present it for display, you can choose the precision of the display to whatever you want by string conversion. Presentation is a display issue, not a storage thing.

    0 讨论(0)
  • 2020-11-27 09:50

    You can use .toFixed() to for float value 2 digits

    Exampale

    let newValue = parseFloat(9.990000).toFixed(2)
    
    //output
    9.99
    
    0 讨论(0)
  • 2020-11-27 09:51

    You can use toFixed() to do that

    var twoPlacedFloat = parseFloat(yourString).toFixed(2)
    
    0 讨论(0)
  • 2020-11-27 09:51

    If you need performance (like in games):

    Math.round(number * 100) / 100
    

    It's about 100 times as fast as parseFloat(number.toFixed(2))

    http://jsperf.com/parsefloat-tofixed-vs-math-round

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