JavaScript displaying a float to 2 decimal places

JavascriptFloating PointPrecision

Javascript Problem Overview


I wanted to display a number to 2 decimal places.

I thought I could use toPrecision(2) in JavaScript .

However, if the number is 0.05, I get 0.0500. I'd rather it stay the same.

See it on JSbin.

What is the best way to do this?

I can think of coding a few solutions, but I'd imagine (I hope) something like this is built in?

Javascript Solutions


Solution 1 - Javascript

float_num.toFixed(2);

Note:toFixed() will round or pad with zeros if necessary to meet the specified length.

Solution 2 - Javascript

You could do it with the toFixed function, but it's buggy in IE. If you want a reliable solution, look at my answer here.

Solution 3 - Javascript

Don't know how I got to this question, but even if it's many years since this has been asked, I would like to add a quick and simple method I follow and it has never let me down:

var num = response_from_a_function_or_something();

var fixedNum = parseFloat(num).toFixed( 2 );

Solution 4 - Javascript

number.parseFloat(2) works but it returns a string.

If you'd like to preserve it as a number type you can use:

Math.round(number * 100) / 100

Solution 5 - Javascript

Try toFixed instead of toPrecision.

Solution 6 - Javascript

function round(value, decimals) { return Number(Math.round(value+'e'+decimals)+'e-'+decimals); }

>round(1.005, 2); // return 1.01

>round(1.004, 2); // return 1 instead of 1.00

The answer is following this link: http://www.jacklmoore.com/notes/rounding-in-javascript/

Solution 7 - Javascript

with toFixed you can set length of decimal points like this:

let number = 6.1234
number.toFixed(2) // '6.12'

but toFixed returns a string and also if number doesn't have decimal point at all it will add redundant zeros.

let number = 6
number.toFixed(2) // '6.00'

to avoid this you have to convert the result to a number. you can do this with these two methods:

let number1 = 6
let number2 = 6.1234

// method 1
parseFloat(number1.toFixed(2)) // 6
parseFloat(number2.toFixed(2)) // 6.12

// method 2
+number1.toFixed(2) // 6
+number2.toFixed(2) // 6.12

Solution 8 - Javascript

You could try mixing Number() and toFixed().

Have your target number converted to a nice string with X digits then convert the formated string to a number.

Number( (myVar).toFixed(2) )


See example below:

var myNumber = 5.01;
var multiplier = 5;
$('#actionButton').on('click', function() {
  $('#message').text( myNumber * multiplier );
});

$('#actionButton2').on('click', function() {
  $('#message').text( Number( (myNumber * multiplier).toFixed(2) ) );
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<button id="actionButton">Weird numbers</button>
<button id="actionButton2">Nice numbers</button>

<div id="message"></div>

Solution 9 - Javascript

> The toFixed() method formats a number using fixed-point notation.

and here is the syntax

numObj.toFixed([digits])

digits argument is optional and by default is 0. And the return type is string not number. But you can convert it to number using

numObj.toFixed([digits]) * 1

It also can throws exceptions like TypeError, RangeError

Here is the full detail and compatibility in the browser.

Solution 10 - Javascript

I used this way if you need 2 digits and not string type.

    const exFloat = 3.14159265359;
    
    console.log(parseFloat(exFloat.toFixed(2)));

Solution 11 - Javascript

let a = 0.0500
a.toFixed(2);

//output
0.05

Solution 12 - Javascript

There's also the Intl API to format decimals according to your locale value. This is important specially if the decimal separator isn't a dot "." but a comma "," instead, like it is the case in Germany.

Intl.NumberFormat('de-DE').formatToParts(0.05).reduce((acc, {value}) => acc += value, '');

Note that this will round to a maximum of 3 decimal places, just like the round() function suggested above in the default case. If you want to customize that behavior to specify the number of decimal places, there're options for minimum and maximum fraction digits:

Intl.NumberFormat('de-DE', {minimumFractionDigits: 3}).formatToParts(0.05)

Solution 13 - Javascript

I have made this function. It works fine but returns string.

function show_float_val(val,upto = 2){
  var val = parseFloat(val);
  return val.toFixed(upto);
}

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
QuestionalexView Question on Stackoverflow
Solution 1 - JavascriptJason McCrearyView Answer on Stackoverflow
Solution 2 - JavascriptElias ZamariaView Answer on Stackoverflow
Solution 3 - JavascriptpanosView Answer on Stackoverflow
Solution 4 - JavascriptrnmaloneView Answer on Stackoverflow
Solution 5 - JavascriptcasablancaView Answer on Stackoverflow
Solution 6 - JavascriptHuy NguyenView Answer on Stackoverflow
Solution 7 - JavascriptcodegamesView Answer on Stackoverflow
Solution 8 - JavascriptGeorge-Paul B.View Answer on Stackoverflow
Solution 9 - JavascriptSunil GargView Answer on Stackoverflow
Solution 10 - Javascriptl2DView Answer on Stackoverflow
Solution 11 - JavascriptRizwanView Answer on Stackoverflow
Solution 12 - JavascriptlmerinoView Answer on Stackoverflow
Solution 13 - JavascriptSyed Nurul IslamView Answer on Stackoverflow