js realizes the thousandth of numerical value and the method of saving decimal. of recommendation

  • 2021-07-06 10:14:18
  • OfStack

Examples are as follows:


/**
    *  Will the value 4 Shed 5 Formatting after entering .
    *
    * @param num  Numerical value (Number Or String)
    * @param cent  Decimal places to keep (Number)
    * @param isThousand  Do you need a thousandth  0: No need ,1: Need ( Numeric type );
    * @return  Format string , Such as '1,234,567.45'
    * @type String
    */
   function formatNumber(num,cent,isThousand) {
    num = num.toString().replace(/\$|\,/g,'');

    //  Check that the passed-in value is of numeric type 
     if(isNaN(num))
      num = "0";

    //  Get symbols ( Positive / Negative number )
    sign = (num == (num = Math.abs(num)));

    num = Math.floor(num*Math.pow(10,cent)+0.50000000001); //  Converts the specified decimal place to an integer first . Excess decimal places 4 Shed 5 Into 
    cents = num%Math.pow(10,cent);       //  Find the decimal value 
    num = Math.floor(num/Math.pow(10,cent)).toString();  //  Find the integer bit value 
    cents = cents.toString();        //  Convert decimal places into strings , So as to find the length of decimal places 

    //  Complement the decimal place to the specified number of digits 
    while(cents.length<cent)
     cents = "0" + cents;

    if(isThousand) {
     //  Formatting integer parts in thousandths .
     for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
      num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
    }

    if (cent > 0)
     return (((sign)?'':'-') + num + '.' + cents);
    else
     return (((sign)?'':'-') + num);
   }

Related articles: