18

With .toFixed(2) I always get 2 decimals, even if the number is 2.00

Can I get "2" instead?

Example:

  • 2.00 => 2
  • 2.05 => 2.05
  • 2.053435 => 2.05
  • 2.057435 => 2.06
Elfy
  • 1,485
  • 6
  • 16
  • 33
  • 2
    possible duplicate of [Round to at most 2 decimal places in JavaScript](http://stackoverflow.com/questions/11832914/round-to-at-most-2-decimal-places-in-javascript) – Vucko Aug 26 '15 at 14:42
  • but that also suggets I use toFixed(2) which doesn't work like I want – Elfy Aug 26 '15 at 14:43
  • So use the script from the most voted answer? Here's [your example](http://jsfiddle.net/af3qg9bc/) – Vucko Aug 26 '15 at 14:46

2 Answers2

43

function toFixedIfNecessary( value, dp ){
  return +parseFloat(value).toFixed( dp );
}

console.log( toFixedIfNecessary( 1.999, 2 ));    // 2
console.log( toFixedIfNecessary( 2, 2 ));        // 2
console.log( toFixedIfNecessary( 2.1, 2 ));      // 2.1
console.log( toFixedIfNecessary( 2.05, 2 ));     // 2.05
console.log( toFixedIfNecessary( 2.05342, 2 ));  // 2.05
console.log( toFixedIfNecessary( 2.04999, 2 ));  // 2.05
console.log( toFixedIfNecessary( 2.04499, 2 ));  // 2.04
console.log( toFixedIfNecessary( 2.053435, 2 )); // 2.05
console.log( toFixedIfNecessary( 2.057435, 2 )); // 2.06
MT0
  • 113,669
  • 10
  • 50
  • 103
2

You can use Math.round():

var number = 2.005;
var number2 = 2.558934;
var number3 = 1.005;

function round(value, decimals) {
    return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}

console.log(round(number, 2)) // > 2.01
console.log(round(number2, 2)) // > 2.56
console.log(round(number3, 2)) // > 1.01
baao
  • 67,185
  • 15
  • 124
  • 181
  • `Math.round( 1.005 * 100 ) / 100` returns `1` – MT0 Aug 26 '15 at 14:49
  • 1
    And it should return 1, because we want maximum 2 decimal places, but if you input 1.05 it will return 1.05, or if we input 1.051264 it will return 1.05 – Neven Ignjic Aug 26 '15 at 14:56
  • 3
    @NevenIgnjic `1.005` to 2dp is `1.01` not `1` – MT0 Aug 26 '15 at 14:58
  • It depends, I came across two types of rounding when the input is at the half between to values it needs to snap. 1. Snap to higher or lower value 2. Snap to closest even or odd number So it all depends what kind of software is calculating this, but to the OP these things don't matter. – Neven Ignjic Aug 26 '15 at 15:01