Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format numbers in JavaScript?

Tags:

javascript

How to format numbers in JavaScript?


  • JavaScript culture sensitive currency formatting
like image 324
Daniel Silveira Avatar asked Oct 21 '08 14:10

Daniel Silveira


People also ask

How do I get 2 decimal places in JavaScript?

To limit the number of digits up to 2 places after the decimal, the toFixed() method is used. The toFixed() method rounds up the floating-point number up to 2 places after the decimal.

How do you represent a number in JavaScript?

In JavaScript, a number can be a primitive value (typeof = number) or an object (typeof = object). The valueOf() method is used internally in JavaScript to convert Number objects to primitive values. There is no reason to use it in your code. All JavaScript data types have a valueOf() and a toString() method.

What is format method in JavaScript?

format() The format() method returns a string with a language-specific representation of the list.

Can you format a number with CSS?

Is it possible to format numbers with CSS? That is: decimal places, decimal separator, thousands separator, etc. You can't but you really should be able to. After all, 50,000 or 50000 or 50,000.00 are all the same 'data' they're just presented differently which is what CSS is for.


1 Answers

The best you have with JavaScript is toFixed() and toPrecision() functions on your numbers.

var num = 10;
var result = num.toFixed(2); // result will equal 10.00

num = 930.9805;
result = num.toFixed(3); // result will equal 930.981

num = 500.2349;
result = num.toPrecision(4); // result will equal 500.2

num = 5000.2349;
result = num.toPrecision(4); // result will equal 5000

num = 555.55;
result = num.toPrecision(2); // result will equal 5.6e+2

Currency, commas, and other formats will have to be either done by you or a third party library.

like image 70
SaaS Developer Avatar answered Oct 29 '22 18:10

SaaS Developer