user2043267
user2043267

Reputation: 71

Need help to round up decimals Javascript

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

Upvotes: 2

Views: 67

Answers (3)

Sotiris Kiritsis
Sotiris Kiritsis

Reputation: 3346

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

Upvotes: 1

Bathsheba
Bathsheba

Reputation: 234855

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.

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1075337

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

Upvotes: 1

Related Questions