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

62,488

Solution 1

You're looking for toFixed:

var x = 4.3455;
alert(x.toFixed(2)); // alerts 4.35 -- not what you wanted!

...but it looks like you want to truncate rather than rounding, so:

var x = 4.3455;
x = Math.floor(x * 100) / 100;
alert(x.toFixed(2)); // alerts 4.34

Solution 2

As T.J answered, the toFixed method will do the appropriate rounding if necessary. It will also add trailing zeroes, which is not always ideal.

(4.55555).toFixed(2);
//-> "4.56"

(4).toFixed(2);
//-> "4.00"

If you cast the return value to a number, those trailing zeroes will be dropped. This is a simpler approach than doing your own rounding or truncation math.

+parseFloat((4.55555).toFixed(2));
//-> 4.56

+parseFloat((4).toFixed(2));
//-> 4

Solution 3

Warning! The currently accepted solution fails in some cases, e.g. with 4.27 it wrongly returns 4.26.

Here is a general solution that works always.

(Maybe I should put this as a comment, but at the time of this writing, I don't have the required reputation)

Solution 4

If you don't want rounding to 2 decimal places, use toFixed() to round to n decimal places and chop all those off but 2:

var num = 4.3455.toFixed(20);
alert(num.slice(0, -18));
//-> 4.34

Note that this does have the slight downside of rounding when the number of decimal places passed to toFixed() is less than the number of decimal places of the actual number passed in and those decimal places are large numbers. For instance (4.99999999999).toFixed(10) will give you 5.0000000000. However, this isn't a problem if you can ensure the number of decimal places will be lower than that passed to toFixed(). It does, however, make @TJ's solution a bit more robust.

Solution 5

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)
)

​​​​​​

Share:
62,488
dotty
Author by

dotty

Hmm not alot really.

Updated on July 09, 2022

Comments

  • dotty
    dotty almost 2 years

    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
    

    I don't want to round the number up or down, just limit the amount of numbers shown after the decimal place to 2.

  • dotty
    dotty over 13 years
    You are right, i was using toFixed() but i was also using parseInt which was converting my float to a number and toFixed() was always returning xx.00 !
  • Andy E
    Andy E over 13 years
    You were right about the dupe. When I read that it clicked in my head that I saw it too, a day or so ago :-)
  • T.J. Crowder
    T.J. Crowder over 13 years
    @dotty: Ah, yes, parseInt will convert the number to a string, then convert that string back into a number disregarding anything after the decimal. :-) But no need for it in this case, you can call functions on numbers (they automagically get converted from primitives into Number instances).
  • T.J. Crowder
    T.J. Crowder over 13 years
    @Andy E: And yet I can't find it. I gave up, if it's that hard to find, we need a duplicate! :-) (Edit: Ah, you found it. I guess it's just so new that Google hasn't indexed it yet.)
  • Andy E
    Andy E over 13 years
    @TJC: yeah, actually 8 days ago... the concept of time is just lost on me these days!
  • LostInBrittany
    LostInBrittany about 8 years
    Thanks for the casting to number idea!
  • Rémi Santos
    Rémi Santos over 7 years
    The casting idea is brilliant 👌
  • Myndex
    Myndex over 3 years
    Sweet answer — simple, effective, and not particularly obvious. Thank you!