Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: using toLocaleString + Tofixed

Tags:

I need to format a number for a project im working on at work, only problem is that I cant format it how i want.

I convert the number to a localestring using the toLocaleString method which gives me the commas but i also need decimal places, nothing i seem to do works.

var number = 123.322 number = parseFloat(number).toFixed(2) //123.22 number.toLocaleString() //123.22 

The above code just returns the parsefloated number along with the tofixed decimal values but it doesn't add the commas.

How do i get a number to have two decimal places (when the value is 'xx.00') and also be comma separated. Is this possible in JavaScript?

like image 271
Kenziiee Flavius Avatar asked Oct 20 '16 10:10

Kenziiee Flavius


People also ask

How does toFixed work in JavaScript?

toFixed() returns a string representation of numObj that does not use exponential notation and has exactly digits digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length.

What does the toLocaleString () method do in JS?

The toLocaleString() method returns a string with a language-sensitive representation of this date. In implementations with Intl. DateTimeFormat API support, this method simply calls Intl. DateTimeFormat .

Does toFixed round JavaScript?

Note. The toFixed() method will round the resulting value if necessary. The toFixed() method will pad the resulting value with 0's if there are not enough decimal places in the original number. The toFixed() method does not change the value of the original number.

How do I localize a number in JavaScript?

In JavaScript, toLocaleString() is a Number method that is used to convert a number into a locale-specific numeric representation of the number (rounding the result where necessary) and return its value as a string.


2 Answers

You can give an object to .toLocaleString() which describes what you want:

var sNumber = (10123.322).toLocaleString(undefined,  {'minimumFractionDigits':2,'maximumFractionDigits':2}); 

Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

Original:

const fNumber = 10123.322;  const sNumber = parseFloat(fNumber.toFixed(2)).toLocaleString();  console.log(sNumber);

The number is already in decimal/float format on the first line.

  • .toFixed(2) turns it into a string using fixed-point notation.
  • parseFloat() takes that string and turns it back into a float.
  • .toLocaleString() turns it into a string using the local format.
like image 191
Alien426 Avatar answered Oct 24 '22 16:10

Alien426


Just to do it in one line

var num = '12233.3366554'; num = parseFloat(parseFloat(num).toFixed(2)).toLocaleString('en-IN', { useGrouping: true }); 
like image 23
Amey Vartak Avatar answered Oct 24 '22 15:10

Amey Vartak