2

Im trying to round up 2 number and adding them after.

var a = 12.24; var b = 12.27;

i want them to round up to 12.5 so when i add these 2 numbers the result will be 12.5 + 12.5 = 25

11
  • So, you want to round to the nearest 0.5? Commented Sep 21, 2015 at 14:19
  • You want to round the value to the nearest 0.5 irrespective of the decimal value? eg. 12.005, 12.1, 12.49 etc etc... Commented Sep 21, 2015 at 14:22
  • Voted to reopen: duplicate does not show how to round to nearest half. Commented Sep 21, 2015 at 14:22
  • "Bathsheba yes, i want to round to nearest 0,5 Commented Sep 21, 2015 at 14:22
  • 1
    Why not add both numbers before rounding them? It will get a value of 25. Commented Sep 21, 2015 at 14:23

3 Answers 3

1

It's the same as shown in this answer, using a different multiplier/divisor. In that question, they wanted the nearest 10th; in this question, you want the nearest half. So instead of

var num = 12.24;
num = Math.ceil(num * 10) / 10;
alert(num); // 12.24

...we use

var num = 12.24;
num = Math.ceil(num * 2) / 2;
alert(num); // 12.5
Sign up to request clarification or add additional context in comments.

Comments

1

To round to the nearest half, use

Math.round(a / 0.5) * 0.5;

To round up to the nearest half, use

Math.ceil(a / 0.5) * 0.5; But note two things:

  1. Floating point arithmetic might still cause a fractionally-rounded number to be off. (But note that half-rounded numbers can be represented accurately in floating point to the 52nd power of 2).

  2. You can achieve your result by summing the numbers then rounding the result. That will be more numerically stable.

Comments

1

You can try the following. Here is a Jsfiddle.

var a = 12.24;
console.log(roundHalf(a)); // 12.5
var b = 12.27;
console.log(roundHalf(b)); // 12.5
var result = roundHalf(a) + roundHalf(b);
console.log(result); // 25

function roundHalf(num){
    return Math.ceil(num * 2) / 2;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.