2

I have an array of numbers that I would like to round up so that it will always end with #.#0 or #.#5. But when I tried either Math.round or Math.ceil they are returning me integers.

let result = []

const numbers = [
  3.33,  // 3.35
  1.00,  // 1.00
  1.11,  // 1.15
  1.50,  // 1.50
  5.99,  // 6.00
  5.66,  // 7.00
]

result = numbers.map(number => Math.round(number, 2))
result = numbers.map(number => Math.ceil(number, 2))

console.log(result)

This is the result I get

[
  4,
  1,
  2,
  2,
  6,
  6,
]

But I am trying to achieve this result

[
  3.35
  1.00
  1.15
  1.50
  6.00
  7.00
]

let result = []

const numbers = [
  3.33,  // 3.35
  1.00,  // 1.00
  1.11,  // 1.15
  1.50,  // 1.50
  5.99,  // 6.00
  5.66,  // 7.00
]

result = numbers.map(number => Math.round(number, 2))
result = numbers.map(number => Math.ceil(number, 2))

console.log(result)
Liga
  • 3,291
  • 5
  • 34
  • 59

2 Answers2

1

var numbers = [
    3.33,  // 3.35
    1.00,  // 1.00
    1.11,  // 1.15
    1.50,  // 1.50
    5.99,  // 6.00
    5.66,  // 5.7
    2.2    // 2.00
  ]

 console.log(numbers.map(x => {
     let tmp = Number((x * 100).toFixed());
     if(tmp % 5 > 0) tmp += 5 - tmp % 5
     return tmp / 100 
 }))
Ziv Ben-Or
  • 1,149
  • 6
  • 15
  • I just noticed that with the number ````2.20```` it gives me the result of ````2.25```` but it should be ````2.20```` – Liga Feb 03 '20 at 15:37
  • You right, there is a known problem with floating point and binary formt. I fixed the code. For more details: https://stackoverflow.com/questions/588004/is-floating-point-math-broken – Ziv Ben-Or Feb 04 '20 at 06:18
0

Math.round() rounds to the nearest integer. If you want to round to 1/20th you can do Math.round(number*20) / 20.

Or Math.ceil(number*20) / 20 if you always want to round up.

const numbers = [
  3.33,  // 3.35
  1.00,  // 1.00
  1.11,  // 1.15
  1.50,  // 1.50
  5.99,  // 6.00
  5.66,  // 7.00
]

let result = numbers.map(number => Math.ceil(number*20) / 20)

console.log(result)
Thomas
  • 11,958
  • 1
  • 14
  • 23