leora
leora

Reputation: 196861

formatting decimals in javascript

i want to format a number to max of 2 decimals in javascript. i see that there is:

toFixed(2)

but this seems like it would ALWAYS do 2 decimals. i want something that would take: 100.1223334 and convert it to 100.12 but i want this function to convert 100.5 to just 100.5 (since < 2 decimal digits)

whats is the best way of doing this in javascript.

Upvotes: 3

Views: 1581

Answers (2)

PleaseStand
PleaseStand

Reputation: 32112

Use Math.round(number * 100) / 100.

For example, 100.1223 becomes 10012.23, which is rounded to the nearest integer (10012) and then divided by 100 to get 100.12.

Upvotes: 5

Sang Suantak
Sang Suantak

Reputation: 5265

Use Math.round(number). This will round off the number to maximum 2 decimals.

Upvotes: 0

Related Questions