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

JavascriptFloating PointDecimalLimit

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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

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

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 4 - Javascript

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 5 - Javascript

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

​​​​​​

Solution 6 - Javascript

Use toPrecision :)

var y = 67537653.76828732668326;
y = (String(y).indexOf('.') !== -1) ? +y.toPrecision(String(y).indexOf('.') + 2) : +y.toFixed(2);
// => 67537653.76

The 2 in the second line dictates the number of decimal places, this approach returns a number, if you want a string remove the "+" operator.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondottyView Question on Stackoverflow
Solution 1 - JavascriptT.J. CrowderView Answer on Stackoverflow
Solution 2 - JavascriptC. J.View Answer on Stackoverflow
Solution 3 - JavascriptAndy EView Answer on Stackoverflow
Solution 4 - JavascriptSC1000View Answer on Stackoverflow
Solution 5 - JavascriptNVRMView Answer on Stackoverflow
Solution 6 - Javascriptmmgc84View Answer on Stackoverflow