0

Is there a way in javascript or Typescript to format decimal?

For example:

  • 1.33 => 1.35

  • 1.32 => 1.35

All i found was formatting to 2 decimals, but i need it to format to nearest .05

Yousername
  • 1,012
  • 5
  • 15
Drasko
  • 17
  • 3

1 Answers1

0

This function uses Math.round and multiplies and divides by 0.05 because it is to the nearest 0.05.

function tN(n) {
    return Math.round(n / 0.05) * 0.05;
}

console.log(tN(1.33));

console.log(tN(1.32));

console.log(tN(0.05));

console.log(tN(-1.08));

If all outputs have to end in a 5:

function tN(n) {
    return n % 0.1 > 0.05 ? Math.floor(n / 0.05) * 0.05 : Math.ceil(n / 0.05) * 0.05;
}

console.log(tN(1.33));

console.log(tN(1.32));

console.log(tN(0.05));

console.log(tN(-1.08));
Yousername
  • 1,012
  • 5
  • 15
  • Please edit your answer. According to the question's description it is wrong. In the question it is written that `1.32 -> 1.35` but in your answer it is `1.3`. You have created a function that rounds numbers to 0.05, in order to have the logic that the question wants you should use `Math.ceil` instead of `Math.round`. –  Dec 25 '19 at 15:24
  • `Math.ceil` would not work because then inputting 1.08 would give 1.1. – Yousername Dec 25 '19 at 15:26
  • Still for 1.32 you should provide 1.35 so the answer is not accurate. In the question is asked that numbers from .01 to .05 should point to .05 and numbers from .06 to .09 should point to .05 also. –  Dec 25 '19 at 15:32
  • I've created a separate function that outputs only numbers ending in 5. – Yousername Dec 25 '19 at 15:45
  • It was my mistake... 1.32 should be round to 1.30 sry :D – Drasko Dec 25 '19 at 18:27