Can you use decimals in javascript?


Definition and Usage

The toFixed() method converts a number to a string.

The toFixed() method rounds the string to a specified number of decimals.

Note

If the number of decimals are higher than in the number, zeros are added.


Syntax

Parameters

Parameter Description
x Optional.
Number of decimals.
Default is 0 (no decimals)

Return Value

Type Description
A string The representation of a number with (or without) decimals.


More Examples


Browser Support

Number.constructor is an ECMAScript3 (ES3) feature.

ES3 (JavaScript 1999) is fully supported in all browsers:

Chrome IE Edge Firefox Safari Opera
Yes Yes Yes Yes Yes Yes


Originally published in the A Drip of JavaScript newsletter.

One of the more unintuitive aspects of JavaScript, particularly for new developers, is the fact that decimal math doesn't always work as you'd expect it to. Suppose that Worf has exactly $600.90 of 21st century American dollars to trade for a wine of excellent vintage.

var worfsMoney = 600.90;
var bloodWinePrice = 200.30;
var worfsTotal = bloodWinePrice * 3;

// Outputs: false
console.log(worfsMoney >= worfsTotal);

// Outputs: 600.9000000000001
console.log(worfsTotal);

As you can see, simply checking whether Worf has enough money fails because his total doesn't come to exactly $600.90. But why is that?

In JavaScript all numbers are IEEE 754 floating point numbers. Due to the binary nature of their encoding, some decimal numbers cannot be represented with perfect accuracy. This is analagous to how the fraction 1/3 cannot be accurately represented with a decimal number with a finite number of digits. Once you hit the limit of your storage you'll need to round the last digit up or down.

Your first thought might be to try rounding to the second decimal place. Unfortunately, JavaScript's built-in rounding functions only round to the nearest integer.

Your second thought might be to do something like this:

// Outputs: true
console.log(worfsMoney.toFixed(2) >= worfsTotal.toFixed(2));

But even though we get the correct result, using toFixed means that we are just comparing formatted strings rather than actual numbers. And what we really want is a way to get an accurate numeric representation of our numbers.

Fortunately there is an easy way to do that in JavaScript. Instead of representing our money's value as decimal numbers based on dollars, we can just use whole integers of cents.

var worfsMoney = 60090;
var bloodWinePrice = 20030;
var worfsTotal = bloodWinePrice * 3;

// Outputs: true
console.log(worfsMoney >= worfsTotal);

// Outputs: 60090
console.log(worfsTotal);

Because integers can be represented perfectly accurately, just shifting our perspective to treat cents as the basic unit of currency means that we can often avoid the problems of comparisons in floating point arithmetic.

Of course, this doesn't solve all problems. Division of integers and multiplication by decimals may still result in inexact values, but basic integer addition, subtraction, and multiplication will be accurate. (At least until you hit JavaScript's upper limit for numbers.)

Thanks for reading!

Josh Clanton

If precision matters and you require consistent results, here are a few propositions that will return the decimal part of any number as a string, including the leading "0.". If you need it as a float, just add var f = parseFloat( result ) in the end.

If the decimal part equals zero, "0.0" will be returned. Null, NaN and undefined numbers are not tested.

1. String.split

var nstring = (n + ""),
    narray  = nstring.split("."),
    result  = "0." + ( narray.length > 1 ? narray[1] : "0" );

2. String.substring, String.indexOf

var nstring = (n + ""),
    nindex  = nstring.indexOf("."),
    result  = "0." + (nindex > -1 ? nstring.substring(nindex + 1) : "0");

3. Math.floor, Number.toFixed, String.indexOf

var nstring = (n + ""),
    nindex  = nstring.indexOf("."),
    result  = ( nindex > -1 ? (n - Math.floor(n)).toFixed(nstring.length - nindex - 1) : "0.0");

4. Math.floor, Number.toFixed, String.split

var nstring = (n + ""),
    narray  = nstring.split("."),
    result  = (narray.length > 1 ? (n - Math.floor(n)).toFixed(narray[1].length) : "0.0");

Here is a jsPerf link: https://jsperf.com/decpart-of-number/

We can see that proposition #2 is the fastest.

How do you display decimals in JavaScript?

Use the toFixed() method to format a number to 2 decimal places, e.g. num. toFixed(2) . The toFixed method takes a parameter, representing how many digits should appear after the decimal and returns the result.

What are decimals called in JavaScript?

JavaScript has a single numeric datatype called 'number'. This datatype accommodates integers, decimal numbers (also called floating-point numbers) as well as numbers written in scientific notation. These can all be either positive or negative numbers.

How do I round to 2 decimal places in JavaScript?

Use the toFixed() method to round a number to 2 decimal places, e.g. const result = num. toFixed(2) . The toFixed method will round and format the number to 2 decimal places.

What is the output of 0.1 0.2 in JavaScript?

Conclusion. I was super surprised to learn that 0.1 + 0.2 is actually supposed to equal 0.30000000000000004 in JavaScript because of floating point math.