airuikun / technology-blog

个人博客,前端技术收集,一起共同学习与成长
3.18k stars 292 forks source link

解释一下在js里,0.1+0.2为什么等于0.30000000000000004,如何通过代码解决这个问题? #27

Open airuikun opened 5 years ago

airuikun commented 5 years ago

第二问我给个简单的思路吧:将浮点数转换为整数来进行计算。

答案不唯一,欢迎提供更好的idea

fairyly commented 5 years ago

原因:

解决方案:

参考:

lylwanan commented 5 years ago
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));
ghost commented 5 years ago

Math.round((0.1+0.2)*100)/100

shenyanggg commented 5 years ago

1.取整 2.根据业务避免这样的代码

nelsonkuang commented 5 years ago

来个全能版

      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
ghost commented 5 years ago

谢谢,受教了!发自我的华为手机-------- 原始邮件 --------主题: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.

zjians commented 5 years ago

js中比较浮点数相等应该使用js提供的最小精度 EPSILON : 差值小于最小精度就是相等! Math.abs(0.1 + 0.2 - 0.3) <= Number.EPSILON

webkonglong commented 5 years ago

这个转化整数就能处理,难得是和number有关的是‘1212121212121212121212121212121’ + '12312312312312312312312312321312312312' = ? 答案要求是一个字符串,不要是科学计数法。

ghrace commented 5 years ago

parseFloat((0.1 + 0.2).toFixed(10))

sanmuw commented 4 years ago

function tofixedNum(num) { let n=0 numarr.forEach((item,index) => { if(item.toString().includes('.')) {

   let tem = num.toString().split('.')[1].length
   if (tem>n) {
     n = tem
 }

} }) return n; } ((.1+.2).toFixed(tofixedNum([.1,.2])))*1