0

I’m trying to round a number to the next highest 0.1 decimal point. For example if I have 2.51 I want it to be rounded up to 2.6, 3.91 to 4, 4.12 to 4.2 etc.

I’ve tried the following however this just rounds to nearest nearest 0.1 decimal and not the next 0.1

4.41.toFixed(1);

This rounds to 4.4 not 4.5 as intended

Liam
  • 27,717
  • 28
  • 128
  • 190
Davei6
  • 11
  • 2
  • You need to use `Math.round` – Utkarsh Dubey Oct 09 '17 at 12:39
  • Possible duplicate of [How do you round to 1 decimal place in Javascript?](https://stackoverflow.com/questions/7342957/how-do-you-round-to-1-decimal-place-in-javascript) – Liam Oct 09 '17 at 12:39
  • 1
    Multiply the number by then, use .ceil(), then divide by 10. – Dellirium Oct 09 '17 at 12:40
  • Note that this is not mathematical correct as this should first be done when the secondary decimal is 5 or more. Ref: https://math.stackexchange.com/questions/3448/rules-for-rounding-positive-and-negative-numbers# – McMuffinDK Oct 09 '17 at 12:55

5 Answers5

4

Divide, ceil and then multiply and format.

(Math.ceil(num * 10) / 10).toFixed(1);
alex
  • 479,566
  • 201
  • 878
  • 984
1
(Math.ceil(num * 10) / 10).toFixed(1);

would do it.

Note that this will still leave trailing digits on the 16th significant figure though due to the fact that floating point numbers cannot, in general, be truncated exactly to 1 decimal place. 4.5 works as it's a dyadic rational. The closest double to 2.6, for example, is 2.600000000000000088817841970012523233890533447265625.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

Just multiply the number with 10, use Math.ceil() and then divide it by 10.

Math.ceil(num * 10) / 10
cyr_x
  • 13,987
  • 2
  • 32
  • 46
0
Math.ceil(4.41*10)/10 // 4.5

More generally,

Math.ceil(x*10)/10
falloutx
  • 81
  • 1
  • 6
0

You could add an offset of 0.049999999 and take the fixed value.

function round(v) {
    return (v + 0.049999999).toFixed(1);
}

console.log(round(2.51)); // 2.6
console.log(round(3.91)); // 4.0
console.log(round(4.12)); // 4.2
console.log(round(1));    // 4.2
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392