数字丢失精度问题

  • 由于 js 的特殊性,它在计算小数时经常会丢失精度:
    • 0.1 + 0.2 = 0.30000000000000004
  • 这是 js 的特点,我们需要解决一下

解决方案有两种:

  1. 将计算的两个小数字先扩大倍数为整数,计算结果,得到结果之后,再缩小倍数
    1. 这种方案一般情况可以没有问题,但是一些特殊的数字也会出问题
35.41 * 100 - 0.02 * 100 // 出问题
  1. 使用第三方包 Math.js
    1. 下载第三方包:npm i mathjs
    2. 导入第三方包:import * as Math from 'mathjs'
    3. 计算数据
// 加
const add = Math.number(Maht.add(Math.bignumber(0.1), Math.bignumber(0.2)))

// 减
const sub = Math.number(Maht.subtract(Math.bignumber(0.1), Math.bignumber(0.2)))

 砍价场景代码:

import { Component } from 'react'
// import Math from 'mathjs'
import './style/index.css'
import * as Math from 'mathjs'

class App extends Component {
  state = {
    list: [
      {
        id: 1,
        name: '超级好吃的棒棒糖',
        price: 18.8,
        info: '开业大酬宾,全场8折',
      },
      {
        id: 2,
        name: '超级好吃的大鸡腿',
        price: 34.2,
        info: '开业大酬宾,全场8折',
      },
      {
        id: 3,
        name: '超级无敌的冰激凌',
        price: 14.2,
        info: '开业大酬宾,全场8折',
      },
    ],
  }
  cutPrice = (id, price) => {
    // 根据 id 找到对应商品,将价格进行修改
    const newList = this.state.list.map((item) => {
      if (item.id === id) {
        return {
          ...item,
          price: Math.number(
            Math.subtract(Math.bignumber(item.price), Math.bignumber(price))
          ),
        }
      } else {
        return item
      }
    })
    this.setState({
      list: newList,
    })
  }
  render() {
    return (
      <div className="parent">
        <h1>父组件</h1>
        {this.state.list.map((item) => (
          <Child cutPrice={this.cutPrice} data={item} key={item.id} />
        ))}
      </div>
    )
  }
}

猜你喜欢

转载自blog.csdn.net/chenbing922886/article/details/128876916
今日推荐