[javascript] How can I round a number in JavaScript? .toFixed() returns a string?

Am I missing something here?

var someNumber = 123.456;
someNumber = someNumber.toFixed(2);
alert(typeof(someNumber));
//alerts string

Why does .toFixed() return a string?

I want to round the number to 2 decimal digits.

This question is related to javascript types rounding

The answer is


Why not * the result by 1 i.e

someNumber.toFixed(2) * 1


May be too late to answer but you can multiple the output with 1 to convert to number again, here is an example.

_x000D_
_x000D_
const x1 = 1211.1212121;
const x2 = x1.toFixed(2)*1;
console.log(typeof(x2));
_x000D_
_x000D_
_x000D_


For others like me that happen upon this very old question, a modern solution:

const roundValue = (num, decimals = 2) => {
    let scaling = 10 ** decimals;
    return Math.round((num + Number.EPSILON) * scaling) / scaling;
}

ref: https://stackoverflow.com/a/11832950


What would you expect it to return when it's supposed to format a number ? If you have a number you can't pretty much do anything with it because e.g.2 == 2.0 == 2.00 etc. so it has to be a string.


You can simply use a '+' to convert the result to a number.

var x = 22.032423;
x = +x.toFixed(2); // x = 22.03

I've solved this problem by changing this:

someNumber = someNumber.toFixed(2)

...to this:

someNumber = +someNumber.toFixed(2);

However this will convert the number to a string and parse it again, which will have a significant impact on performance. If you care about performance or type safety, check the the other answers as well.


Here's a slightly more functional version of the answer m93a provided.

const toFixedNumber = (toFixTo = 2, base = 10) => num => {
  const pow = Math.pow(base, toFixTo)
  return +(Math.round(num * pow) / pow)
}

const oneNumber = 10.12323223

const result1 = toFixedNumber(2)(oneNumber) // 10.12
const result2 = toFixedNumber(3)(oneNumber) // 10.123

// or using pipeline-operator
const result3 = oneNumber |> toFixedNumber(2) // 10.12

Of course it returns a string. If you wanted to round the numeric variable you'd use Math.round() instead. The point of toFixed is to format the number with a fixed number of decimal places for display to the user.


Because its primary use is displaying numbers? If you want to round numbers, use Math.round() with apropriate factors.


You should use it like below.

var someNumber: number = 0.000000;
someNumber = Number(someNumber.toFixed(2))

I solved it with converting it back to number using JavaScript's Number() function

var x = 2.2873424;
x = Number(x.toFixed(2));

Number.prototype.toFixed is a function designed to format a number before printing it out. It's from the family of toString, toExponential and toPrecision.

To round a number, you would do this:

someNumber = 42.008;
someNumber = Math.round( someNumber * 1e2 ) / 1e2;
someNumber === 42.01;

// if you need 3 digits, replace 1e2 with 1e3 etc.
// or just copypaste this function to your code:

function toFixedNumber(num, digits, base){
  var pow = Math.pow(base||10, digits);
  return Math.round(num*pow) / pow;
}

.

Or if you want a “native-like” function, you can extend the prototype:

Number.prototype.toFixedNumber = function(digits, base){
  var pow = Math.pow(base||10, digits);
  return Math.round(this*pow) / pow;
}
someNumber = 42.008;
someNumber = someNumber.toFixedNumber(2);
someNumber === 42.01;


//or even hexadecimal

someNumber = 0xAF309/256  //which is af3.09
someNumber = someNumber.toFixedNumber(1, 16);
someNumber.toString(16) === "af3.1";

However, bear in mind that polluting the prototype is considered bad when you're writing a module, as modules shouldn't have any side effects. So, for a module, use the first function.


To supply an example of why it has to be a string:

If you format 1.toFixed(2) you would get '1.00'.

This is not the same as 1, as 1 does not have 2 decimals.


I know JavaScript isn't exactly a performance language, but chances are you'd get better performance for a rounding if you use something like: roundedValue = Math.round(value * 100) * 0.01


Why not use parseFloat?

var someNumber = 123.456;
someNumber = parseFloat(someNumber.toFixed(2));
alert(typeof(someNumber));
//alerts number

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to types

Cannot invoke an expression whose type lacks a call signature How to declare a Fixed length Array in TypeScript Typescript input onchange event.target.value Error: Cannot invoke an expression whose type lacks a call signature Class constructor type in typescript? What is dtype('O'), in pandas? YAML equivalent of array of objects in JSON Converting std::__cxx11::string to std::string Append a tuple to a list - what's the difference between two ways? How to check if type is Boolean

Examples related to rounding

How to round a numpy array? How to pad a string with leading zeros in Python 3 Python - round up to the nearest ten How to round a Double to the nearest Int in swift? Using Math.round to round to one decimal place? How to round to 2 decimals with Python? Rounding to 2 decimal places in SQL Rounding to two decimal places in Python 2.7? Round a floating-point number down to the nearest integer? Rounding BigDecimal to *always* have two decimal places