为什么在javascript中添加浮动会产生奇怪的结果?
我有如下javascript代码:为什么在javascript中添加浮动会产生奇怪的结果?,javascript,floating-point,Javascript,Floating Point,我有如下javascript代码: var strikePrice = parseFloat(this.props.data.strike).toFixed(1); var commission = parseFloat(this.props.commission / 100).toFixed(2); var callInMoney = parseFloat(strikePrice + this.state.callPrice + commission).toFixed(2); var putI
var strikePrice = parseFloat(this.props.data.strike).toFixed(1);
var commission = parseFloat(this.props.commission / 100).toFixed(2);
var callInMoney = parseFloat(strikePrice + this.state.callPrice + commission).toFixed(2);
var putInMoney = parseFloat(strikePrice - this.state.putPrice - commission).toFixed(2);
console.log("strikePrice: " + strikePrice + " commission: " + commission);
console.log("callprice: " + this.state.callPrice + " putprice: " + this.state.putPrice);
console.log("call: " + callInMoney + " put: " + putInMoney);
输出是这样的:
strikePrice: 34.0 commission: 0.08
callprice: 0 putprice: 0
call: 34.00 put: 33.92
这是错误的。看涨期权应该是34.08(高8美分),就像看跌期权低8美分一样
为什么结果不正确
多谢各位
Matt此表达式:
strikePrice+this.state.callPrice+佣金
计算为该值:
“34.000.08”
因为commission
是一个字符串值,这是因为[toFixed()][1]
接受一个整数并返回一个字符串
您需要重构代码,以便commission
是一个浮点值,或者在第3行的参数上再次调用parseFloat()
我无法评论为什么投入资金
对你有效。对我来说,它给了“NaN”
返回一个字符串,所以实际上你在做一些字符串连接,而不是你期望的算术
看看当你打印出你的初始添加时会发生什么
var-strikePrice=parseFloat('34')。toFixed(1);
var佣金=parseFloat('0.08')。toFixed(2);
控制台日志(删除价格+0+佣金)
toFixed将它们转换为字符串,如果您想继续将它们视为数字,请使用parseFloat或Number method。您通常希望对单个值使用parseFloat()
,而不是计算结果。按此顺序,+
可以连接而不是添加。谢谢。既然你已经指出了这一点,它应该是显而易见的:)谢谢。现在有道理了。当我查看它时,我没有意识到toFixed会返回字符串。