Dennis Martinez
Dennis Martinez

Reputation: 6512

Is there a way to round a decimal place to the nearest whole in javascript?

I have a number with decimal places and I am wondering if it's possible to round the decimal to the nearest whole using javascript?

My number is: 4.59

I need my number to round to: 4.60

Upvotes: 4

Views: 1887

Answers (4)

Jakub Konecki
Jakub Konecki

Reputation: 46008

Use the toFixed() method.

More detailed information at: MDN :: toFixed

Upvotes: 2

Spycho
Spycho

Reputation: 7788

I propose you do what Daff suggests, but if you want the trailing "0", you will need to add it onto the string:

var num = 4.59;
var rounded = num.toFixed(1) + '0';

Also, if you want the number as a number rather than a string, use:

Math.round(num * 10);

As Emil suggested. If you then want to display it with the trailing 0, do:

Math.round(num * 10).toFixed(2);

Upvotes: 0

Emil Ivanov
Emil Ivanov

Reputation: 37633

var x = 4.5678;
Math.round(x * 10) / 10; // 4.6
Math.round(x * 100) / 100; // 4.57

Where the number of 0s of multiplication and division is the decimal point you are aiming for.

Upvotes: 0

Daff
Daff

Reputation: 44215

Use Number.toFixed(number of decimal places):

var num = 4.59;
var rounded = num.toFixed(1);

Upvotes: 9

Related Questions