Formatting a number with exactly two decimals in JavaScript

后端 未结 30 2285
广开言路
广开言路 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:50

    You could also use the .toPrecision() method and some custom code, and always round up to the nth decimal digit regardless the length of int part.

    function glbfrmt (number, decimals, seperator) {
        return typeof number !== 'number' ? number : number.toPrecision( number.toString().split(seperator)[0].length + decimals);
    }
    

    You could also make it a plugin for a better use.

    0 讨论(0)
  • 2020-11-21 06:57

    Here's a TypeScript implementation of https://stackoverflow.com/a/21323330/916734. It also dries things up with functions, and allows for a optional digit offset.

    export function round(rawValue: number | string, precision = 0, fractionDigitOffset = 0): number | string {
      const value = Number(rawValue);
      if (isNaN(value)) return rawValue;
    
      precision = Number(precision);
      if (precision % 1 !== 0) return NaN;
    
      let [ stringValue, exponent ] = scientificNotationToParts(value);
    
      let shiftExponent = exponentForPrecision(exponent, precision, Shift.Right);
      const enlargedValue = toScientificNotation(stringValue, shiftExponent);
      const roundedValue = Math.round(enlargedValue);
    
      [ stringValue, exponent ] = scientificNotationToParts(roundedValue);
      const precisionWithOffset = precision + fractionDigitOffset;
      shiftExponent = exponentForPrecision(exponent, precisionWithOffset, Shift.Left);
    
      return toScientificNotation(stringValue, shiftExponent);
    }
    
    enum Shift {
      Left = -1,
      Right = 1,
    }
    
    function scientificNotationToParts(value: number): Array<string> {
      const [ stringValue, exponent ] = value.toString().split('e');
      return [ stringValue, exponent ];
    }
    
    function exponentForPrecision(exponent: string, precision: number, shift: Shift): number {
      precision = shift * precision;
      return exponent ? (Number(exponent) + precision) : precision;
    }
    
    function toScientificNotation(value: string, exponent: number): number {
      return Number(`${value}e${exponent}`);
    }
    
    0 讨论(0)
  • 2020-11-21 06:57

    100% working!!! Try it

    <html>
         <head>
          <script>
          function replacePonto(){
            var input = document.getElementById('qtd');
            var ponto = input.value.split('.').length;
            var slash = input.value.split('-').length;
            if (ponto > 2)
                    input.value=input.value.substr(0,(input.value.length)-1);
    
            if(slash > 2)
                    input.value=input.value.substr(0,(input.value.length)-1);
    
            input.value=input.value.replace(/[^0-9.-]/,'');
    
            if (ponto ==2)
    	input.value=input.value.substr(0,(input.value.indexOf('.')+3));
    
    if(input.value == '.')
    	input.value = "";
                  }
          </script>
          </head>
          <body>
             <input type="text" id="qtd" maxlength="10" style="width:140px" onkeyup="return replacePonto()">
          </body>
        </html>

    0 讨论(0)
  • 2020-11-21 06:59

    Here is my 1-line solution: Number((yourNumericValueHere).toFixed(2));

    Here's what happens:

    1) First, you apply .toFixed(2) onto the number that you want to round off the decimal places of. Note that this will convert the value to a string from number. So if you are using Typescript, it will throw an error like this:

    "Type 'string' is not assignable to type 'number'"

    2) To get back the numeric value or to convert the string to numeric value, simply apply the Number() function on that so-called 'string' value.

    For clarification, look at the example below:

    EXAMPLE: I have an amount that has upto 5 digits in the decimal places and I would like to shorten it to upto 2 decimal places. I do it like so:

    var price = 0.26453;
    var priceRounded = Number((price).toFixed(2));
    console.log('Original Price: ' + price);
    console.log('Price Rounded: ' + priceRounded);

    0 讨论(0)
  • 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.
    */

    0 讨论(0)
  • 2020-11-21 07:00

    I don't know why can't I add a comment to a previous answer (maybe I'm hopelessly blind, dunno), but I came up with a solution using @Miguel's answer:

    function precise_round(num,decimals) {
       return Math.round(num*Math.pow(10, decimals)) / Math.pow(10, decimals);
    }
    

    And its two comments (from @bighostkim and @Imre):

    • Problem with precise_round(1.275,2) not returning 1.28
    • Problem with precise_round(6,2) not returning 6.00 (as he wanted).

    My final solution is as follows:

    function precise_round(num,decimals) {
        var sign = num >= 0 ? 1 : -1;
        return (Math.round((num*Math.pow(10,decimals)) + (sign*0.001)) / Math.pow(10,decimals)).toFixed(decimals);
    }
    

    As you can see I had to add a little bit of "correction" (it's not what it is, but since Math.round is lossy - you can check it on jsfiddle.net - this is the only way I knew how to "fix" it). It adds 0.001 to the already padded number, so it is adding a 1 three 0s to the right of the decimal value. So it should be safe to use.

    After that I added .toFixed(decimal) to always output the number in the correct format (with the right amount of decimals).

    So that's pretty much it. Use it well ;)

    EDIT: added functionality to the "correction" of negative numbers.

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