2

I have this number : -0.0166667 and I would like to get only two floating digits, so the number should be -0.01

I tried this

-0.0166667.toFixed(2)  # gives : -0.02

and also this

Math.round(-0.0166667 * 100) / 100 # also gives : -0.02

But both of them transform the number to -0.02 instead of -0.01

What's wrong here ?

medBouzid
  • 7,484
  • 10
  • 56
  • 86

3 Answers3

3

Use | bitwise or for truncate the fraction part.

var x = (-0.0166667 * 100 | 0) / 100,
    y = (0.0166667 * 100 | 0) / 100;
document.write(x + '<br>' + y);

A better solution which saves the sign, applies flooring and puts the sign back.

function toFixed(x, digits) {
    return (x < 0 ? - 1 : 1) * Math.floor(Math.abs(x) * Math.pow(10, digits)) / Math.pow(10, digits);
}

document.write(toFixed(-0.0166667, 2) + '<br>');
document.write(toFixed(0.0166667, 2) + '<br>');

document.write(toFixed(-0.0166667, 3) + '<br>');
document.write(toFixed(0.0166667, 3) + '<br>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

For numbers between less then zero, Math.ceil truncates without rounding and for numbers greater then zero Math.floor works fine. As your number is less then zer so use Math.ceil instead

Math.ceil(-0.0166667 * 100) / 100

EDIT

Write a custom helper method to truncate floating point

function truncate(num) {
    return num > 0 ? Math.floor(num) : Math.ceil(num);
}

and to round number off by 2 digits use

truncate(num * 100) / 100

Adnan Umer
  • 3,669
  • 2
  • 18
  • 38
1

Math.round will round the number to the nearest integer, so the output of your code is actually correct. What you need is truncation instead of rounding. Here is the simplest way to do that:

function toZero(x) {
  return x > 0 ? Math.floor(x) : Math.ceil(x);
}

function round2digits(x) {
  return toZero(x * 100) / 100;
}

document.write(round2digits(-0.0166)); // prints `-0.01`
Tamas Hegedus
  • 28,755
  • 12
  • 63
  • 97