Limit the amount of number shown after a decimal place in javascript

后端 未结 6 2064
醉酒成梦
醉酒成梦 2020-12-30 20:35

Hay, i have some floats like these

4.3455
2.768
3.67

and i want to display them like this

4.34
2.76
3.67

6条回答
  •  情书的邮戳
    2020-12-30 21:04

    Good news everyone! Since a while there is an alternative: toLocaleString()

    While it isn't exactly made for rounding, there is some usefuls options arguments.

    minimumIntegerDigits

    The minimum number of integer digits to use. Possible values are from 1 > to 21; the default is 1.

    minimumFractionDigits

    The minimum number of fraction digits to use.

    Possible values are from 0 > to 20; the default for plain number and percent formatting is 0; t

    The default for currency formatting is the number of minor unit digits provided by the ISO 4217 currency code list (2 if the list doesn't provide that information).

    maximumFractionDigits

    The maximum number of fraction digits to use.

    Possible values are from 0 > to 20; the default for plain number formatting is the larger of minimumFractionDigits and 3

    The default for currency formatting is the larger of minimumFractionDigits and the number of minor unit digits provided by the ISO 4217 currency code list (2 if the list doesn't provide that information); the default for percent formatting is the larger of minimumFractionDigits and 0.

    minimumSignificantDigits

    The minimum number of significant digits to use. Possible values are from 1 to 21; the default is 1.

    maximumSignificantDigits

    The maximum number of significant digits to use. Possible values are from 1 to 21; the default is 21.

    Example usage:

    var bigNum = 8884858284485 * 4542825114616565
    var smallNum = 88885 / 4545114616565
    
    console.log(bigNum) // Output scientific
    
    console.log(smallNum) // Output scientific
    
    // String
    console.log(
      bigNum.toLocaleString('fullwide', {useGrouping:false})
    ) 
    
    // Return a string, rounded at 12 decimals
    console.log(
      smallNum.toLocaleString('fullwide', {maximumFractionDigits:12})
    )
    
    
    // Return a string, rounded at 8 decimals
    console.log(
      smallNum.toLocaleString('fullwide', {minimumFractionDigits:8, maximumFractionDigits:8})
    )
    
    // Return an Integer, rounded as need, js will convert it back to scientific!
    console.log(
      +smallNum.toLocaleString('fullwide', {maximumFractionDigits:12})
    )
    
    // Return same Integer, don't use parseInt for precision!
    console.log(
      parseInt(smallNum.toLocaleString('fullwide', {maximumFractionDigits:12}))
    )

    But this does not match the question, it is rounding:

    function cutDecimals(number,decimals){
      return number.toLocaleString('fullwide', {maximumFractionDigits:decimals})
    }
    
    console.log(
      cutDecimals(4.3455,2),
      cutDecimals(2.768,2),
      cutDecimals(3.67,2)
    )

    ​​​​​​

提交回复
热议问题