如何将负浮点数(例如-4.00)转换为正数(例如4.00)?
翻转数的最佳方法是将它与-1
相乘:
console.log( -4.00 * -1 ); // 4
如果您不确定数字是正数还是负数,并且不想进行任何条件检查,那么您可以使用Math.abs()
来获取绝对值:
console.log( Math.abs( 7.25 ) ); // 7.25
console.log( Math.abs( -7.25 ) ); // 7.25
console.log( Math.abs( null )) ; // 0
console.log( Math.abs( "Hello" ) ); // NaN
console.log( Math.abs( 7.25-10 ) ); // 2.75
请注意,这将把-50.00
转换为50
(小数位被截断)。如果您希望保留精度,您可以立即在结果上调用toFixed
:
console.log( Math.abs( -50.00 ).toFixed( 2 ) ); // '50.00'
记住toFixed
返回的是一个字符串,而不是一个数字。为了安全地将其转换回数字,您可以使用parseFloat
,在某些情况下会剥离精度,将'50.00'
转化为50
。
取绝对值:Math.abs(-4.00)
var f=-4.00;
if(f<0)
f=-f;
如果您知道值为负数(或想要翻转符号),只需使用-
运算符:
n = -n;
n = Math.abs(n);
value * -1
这是将负数转换为正数的最简单方法。
50.00
的话,它会丢失.00
。有时这很重要。 - Ivan PruchaitoFixed
总是可用的。Math.abs(-50.00).toFixed(2)
将产生 字符串50.00
。 - Sampson