有最大。 2 位小数

问题描述 投票:0回答:3

使用

.toFixed(2)
我总是得到 2 位小数,即使数字是 2.00

我可以选择“2”吗?

示例:

  • 2.00 => 2
  • 2.05 => 2.05
  • 2.053435 => 2.05
  • 2.057435 => 2.06
javascript math tofixed
3个回答
58
投票

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


3
投票

您可以使用

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


0
投票
function toFixedIfNecessary(value, dp){
  return +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

这是@MTO对答案的修改

parseFloat()
没有必要

© www.soinside.com 2019 - 2024. All rights reserved.