4

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

4 Answers 4

9

Use Number.toFixed(number of decimal places):

var num = 4.59;
var rounded = num.toFixed(1);
1
  • Quick, simple, straight to the point. I can't believe how easy it was, I may have been thinking too hard. Thanks! Aug 15, 2011 at 15:09
2

Use the toFixed() method.

More detailed information at: MDN :: toFixed

6
  • 3
    Please refrain linking to w3schools, they're not a representative for javascript. Link to MDN instead: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…
    – Exelian
    Aug 15, 2011 at 14:34
  • @Exelian - That seems arbitrary to me, especially for those of us who find info @ w3schools and not @ mdn (for example). And, what exactly does 'not a representative for javascript mean'?.
    – KevinDTimm
    Aug 15, 2011 at 14:41
  • I've seen another website w3fools, which also attacked this school, for errors which seem trivial (especially for a beginner). They seem to be on a crusade against them.
    – QuentinUK
    Aug 15, 2011 at 14:43
  • 2
    w3fools outlines some rather misleading errors in w3schools. They are on a crusade against w3schools because they feel that they should be better. I think what Exelian meant by not being 'a representative for javascript' is that w3schools does not shape the development of javascript (unlike w3c, who w3schools pretend to be, or MDN).
    – Spycho
    Aug 15, 2011 at 14:52
  • I can't speak for the quality of w3schools lately, but I stopped using it a long time ago because I kept finding mistakes. From reading some of w3fools, it looks like they still have a lot of inaccurate/misleading information. I've also found minor mistakes in Mozilla's documentation, but it's generally pretty good. Aug 15, 2011 at 16:47
0
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.

0

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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.