Have max. 2 decimal places

Elfy picture Elfy · Aug 26, 2015 · Viewed 9.2k times · Source

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

Answer

MT0 picture MT0 · Aug 26, 2015

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