最高 小数点后两位

Elf*_*lfy 0 javascript math tofixed

随着.toFixed(2)我总是得到2位小数,即使数量为2.00

我可以得到“ 2”吗?

例:

  • 2.00 => 2
  • 2.05 => 2.05
  • 2.053435 => 2.05
  • 2.057435 => 2.06

MT0*_*MT0 7

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
Run Code Online (Sandbox Code Playgroud)

  • @homebrand + 将 toFixed 的字符串输出转换回浮点数。在控制台中尝试 `+"2.00"` (4认同)
  • 这是什么咒语?有人可以解释为什么 +parseFloat 有这种行为吗? (2认同)