485

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?

mskfisher
  • 3,291
  • 4
  • 35
  • 48
alex
  • 479,566
  • 201
  • 878
  • 984

14 Answers14

830
float_num.toFixed(2);

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

Jason McCreary
  • 71,546
  • 23
  • 135
  • 174
  • 116
    But it returns string, not float! – Anwar Jun 07 '16 at 09:58
  • 67
    Question author wants to "display" it, so a string is perfect – Christophe Marois Oct 18 '16 at 21:35
  • 18
    And you can always use parseFloat(float_num.toFixed(2)) to convert the string back to float while keeping only two decimals. – Hankrecords Feb 15 '17 at 15:07
  • 4
    @anwar you can't reliably round a float (arguably you can round a float at all) - you'll get something like 0.0500 or even 0.0500000000001. See http://floating-point-gui.de/ – jmc Jan 12 '18 at 00:08
  • 3
    @Hankrecords what you said is not true. If i have '43.01' and I parseFloat then i get 43.01 BUT if i have '43.10' i will get 43.1 :D not what I want. – Lucian Tarna Oct 09 '18 at 15:11
  • @LucianTarna By "while keeping only two decimals" I meant that you won't have more than two. You can't have a 0 as the last decimal digit in a float, it will always truncate. That's why `float_num.toFixed(2)` is needed. – Hankrecords Oct 09 '18 at 15:17
  • @Anwar, if you need a float value, this maybe a better answer for you. https://stackoverflow.com/a/11832950/2125572 – lhrec_106 Aug 23 '19 at 04:22
  • jmc's comment is worth highlighting. It's not possible to represent some floating point values with a finite number of decimal values. The decimal rounding should always be upon converting *from* float to some form of fixed point or decimal value - such as a string, BCD, fixed point integer, but not back to float. Also worth mentioning that float - and therefore Javascript Number - is not suitable for monetary values due to this, unless shifting the integral to the smallest unit of currency (eg count cents, not dollars). – thomasrutter Jul 06 '22 at 00:20
  • float_num.toFixed(2) returns string, so just run parseFloat: float_num =parseFloat(float_num.toFixed(2)) – alex Dec 14 '22 at 21:47
54

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.

Community
  • 1
  • 1
Elias Zamaria
  • 96,623
  • 33
  • 114
  • 148
40

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

rnmalone
  • 1,020
  • 13
  • 25
  • 1
    The internal representation of this might not be what you want. And most likely is something you don't want to be bothered with - representation (and storage) is important. Think of it the same way as you do with booleans. – Herbert Van-Vliet Mar 12 '22 at 09:27
37

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
codegames
  • 1,651
  • 18
  • 16
33

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 );
holaymolay
  • 520
  • 4
  • 17
panos
  • 455
  • 4
  • 3
  • 2
    Why `parseFloat()` there? It should only be used if the number is coming from a string. – alex Jan 13 '16 at 11:00
  • 3
    In some occasions when I get some "data-" attribute value with jquery from an element, if I use only toFixed it produces an error. parseFloat fixes it. – panos Jan 13 '16 at 11:36
  • 2
    Yeah that's what I meant above *if it came from a string*. But using it always is bad advice. – alex Jan 13 '16 at 13:23
25

Try toFixed instead of toPrecision.

casablanca
  • 69,683
  • 7
  • 133
  • 150
18

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/

Huy Nguyen
  • 424
  • 3
  • 10
13

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

    const exFloat = 3.14159265359;
    
    console.log(parseFloat(exFloat.toFixed(2)));
l2D
  • 324
  • 4
  • 8
9

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>
George-Paul B.
  • 544
  • 4
  • 7
4

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.

alex
  • 479,566
  • 201
  • 878
  • 984
Sunil Garg
  • 14,608
  • 25
  • 132
  • 189
3
let a = 0.0500
a.toFixed(2);

//output
0.05
Rizwan
  • 3,741
  • 2
  • 25
  • 22
  • 3
    No, the output is `"0.05"` (running in Chrome dev tools), which is not the same thing – jhamm Mar 01 '21 at 12:40
2

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)
lmerino
  • 173
  • 2
  • 11
1
float_num = parseFloat(float_num.toFixed(2))
alex
  • 1,757
  • 4
  • 21
  • 32
-2

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