Numeric loss of precision issue

 

  • Due to the particularity of js, it often loses precision when calculating decimals:
    • 0.1 + 0.2 = 0.30000000000000004
  • This is a characteristic of js, we need to solve it

There are two solutions:

  1. Expand the calculated two small numbers into multiples first, calculate the result, and then reduce the multiple after getting the result
    1. This scheme can be no problem in general, but some special numbers will also cause problems
35.41 * 100 - 0.02 * 100 // 出问题
  1. Use third-party package Math.js
    1. Download third-party packages:npm i mathjs
    2. Import third-party packages:import * as Math from 'mathjs'
    3. calculate data
// 加
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)))

 Bargain scene code:

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>
    )
  }
}

Guess you like

Origin blog.csdn.net/chenbing922886/article/details/128876916
Recommended