Formatting a number with exactly two decimals in JavaScript

后端 未结 30 2289
广开言路
广开言路 2020-11-21 06:29

I have this line of code which rounds my numbers to two decimal places. But I get numbers like this: 10.8, 2.4, etc. These are not my idea of two decimal places so how I can

30条回答
  •  南笙
    南笙 (楼主)
    2020-11-21 06:59

    /*Due to all told stuff. You may do 2 things for different purposes:
    When showing/printing stuff use this in your alert/innerHtml= contents:
    YourRebelNumber.toFixed(2)*/
    
    var aNumber=9242.16;
    var YourRebelNumber=aNumber-9000;
    alert(YourRebelNumber);
    alert(YourRebelNumber.toFixed(2));
    
    /*and when comparing use:
    Number(YourRebelNumber.toFixed(2))*/
    
    if(YourRebelNumber==242.16)alert("Not Rounded");
    if(Number(YourRebelNumber.toFixed(2))==242.16)alert("Rounded");
    
    /*Number will behave as you want in that moment. After that, it'll return to its defiance.
    */

提交回复
热议问题