0

I want to round the number in specific format in jquery

For ex.

var First = 3.52

if last value after decimal point 2 is less then 3 then it should be round to 0

if last value after decimal point 2 is beetween then 3 to 7 then it should be round to 5

if last value after decimal point 2 is more then 7 then it should be round to 10

Like

if(var First = 1.21) { var Answer = 1.20 }
if(var First = 1.24) { var Answer = 1.25 }
if(var First = 1.28) { var Answer = 1.30 }

i have tried Round and Ceil , Floor but doesnt work for me

Kashyap Patel
  • 1,139
  • 1
  • 13
  • 29

1 Answers1

1

To achieve this you can use Math.round() to the nearest 0.05, like this:

Math.round(number * 20) / 20;

To make it easier you can extract this to a function:

console.log(round(1.21)); // = 1.20
console.log(round(1.24)); // = 1.25
console.log(round(1.28)); // = 1.30

function round(num) {
  return (Math.round(num * 20) / 20).toFixed(2);
}

Note the use of toFixed(2) to force the result to 2 decimal places. Beware that this method returns a string, so if you are planning on doing any calculations with the value you will need to run the result through parseFloat().

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339