Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have max. 2 decimal places

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
like image 910
Elfy Avatar asked Aug 26 '15 14:08

Elfy


2 Answers

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
like image 50
MT0 Avatar answered Oct 20 '22 03:10

MT0


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
like image 28
baao Avatar answered Oct 20 '22 03:10

baao