AngryLeesin

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
  1 随笔 :: 0 文章 :: 0 评论 :: 7 阅读

JS数学运算精度问题

最近项目上JS做加减乘除这类的运算出现了精度不匹配的问题:

例如:

  • 0.1+0.2
  • ->0.30000000000000004
  • 0.3-0.2
  • ->0.09999999999999998
  • 0.3*2
  • ->0.6
  • 0.3*0.2
  • 0.06
  • 0.3/3
  • ->0.09999999999999999

Mathjs这个JS库可以解决这类问题:官网链接

以下是详细的步骤:

  1. 终端执行npm install mathjs

  2. 然后引入所有的库
    import * as math from "mathjs";

  3. 组件代码如下:

<template>
  <article class="article">
    <h3 class="title">{{ title }}</h3>
  </article>
</template>
<script>
import * as math from "mathjs";
export default {
  data() {
    return {
      title: "Hello World",
    };
  },
  methods: {
   
      oldNumberTest() {
      console.log("===oldNumberTest===");
      console.log("0.1+0.2=",0.1+0.2);
      console.log("0.89-0.2=",0.89-0.2);
      console.log("0.1*0.2=",0.1*0.2);
      console.log("0.3/3=",0.3/3);
    },
    mathNumber(){
      console.log("===mathNumber===");
      let sum=this.convert(math.add(math.fraction(0.1), math.fraction(0.2)))
      console.log("math.add(0.1,0.2)=",sum);
       
    },
    convert(value) {
      return(math.format(value, { fraction: "decimal" }));
    },
  },
  created() {
    this.oldNumberTest();
    this.mathNumber();
  },
};
</script>

<style lang="stylus" scoped>
.article
  .title
    border-bottom: solid 3px rgba(red, .2)
</style>

具体的函数请参阅官网

posted on   AngryLeesin  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示