-
Notifications
You must be signed in to change notification settings - Fork 292
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
解释一下在js里,0.1+0.2为什么等于0.30000000000000004,如何通过代码解决这个问题? #27
Comments
原因:
解决方案: 参考: |
function getMax() {
var args = Array.prototype.slice.call(arguments, 0);
return Math.max.apply(null, args.map(item => {
var arr = item.toString().split('.');
return arr.length > 1 ? arr[1].length : 0;
}));
}
function add() {
var args = Array.prototype.slice.call(arguments, 0);
var max = getMax.apply(null, args);
return args.reduce((sum, cur) => sum + cur * max * 10, 0) / 10 * max;
}
// 使用了题主的思路,我个人思路是大数计算
console.log(add(0.1, 0.2)); |
Math.round((0.1+0.2)*100)/100 |
1.取整 |
来个全能版 function add() {
const args = [...arguments]
const maxLen = Math.max.apply(
null,
args.map(item => {
const str = String(item).split('.')[1]
return str ? str.length : 0
})
)
return (
args.reduce((sum, cur) => sum + cur * 10 ** maxLen, 0) / 10 ** maxLen
)
}
console.log(add(0.1, 0.2)) // => 0.3
console.log(add(10, 11)) // => 21
console.log(add(0.001, 0.003)) // => 0.004
console.log(add(0.001, 0.003, 0.005)) // => 0.009
console.log(add(0.001)) // => 0.001 |
谢谢,受教了!发自我的华为手机-------- 原始邮件 --------主题:Re: [airuikun/Weekly-FE-Interview] 解释一下在js里,0.1+0.2为什么等于0.30000000000000004,如何通过代码解决这个问题? (#27)发件人:nelsonkuang 收件人:airuikun/Weekly-FE-Interview 抄送:sanbushusheng ,Comment 来个全能版
function add() { const args = [...arguments] const maxLen = Math.max.apply( null, args.map(item => { const str = String(item).split('.')[1] return str ? str.length : 0 }) ) return ( args.reduce((sum, cur) => sum + cur * 10 ** maxLen, 0) / 10 ** maxLen ) } console.log(add(0.1, 0.2)) // => 0.3 console.log(add(10, 11)) // => 21 console.log(add(0.001, 0.003)) // => 0.004 console.log(add(0.001, 0.003, 0.005)) // => 0.009 console.log(add(0.001)) // => 0.001
—You are receiving this because you commented.Reply to this email directly, view it on GitHub, or mute the thread.
|
js中比较浮点数相等应该使用js提供的最小精度 EPSILON : |
这个转化整数就能处理,难得是和number有关的是‘1212121212121212121212121212121’ + '12312312312312312312312312321312312312' = ? 答案要求是一个字符串,不要是科学计数法。 |
parseFloat((0.1 + 0.2).toFixed(10)) |
function tofixedNum(num) {
} |
第二问我给个简单的思路吧:将浮点数转换为整数来进行计算。
答案不唯一,欢迎提供更好的idea
The text was updated successfully, but these errors were encountered: