前言
在小数计算中经常遇到需要高精度计算的时候,这时候语言对高精度的支持是十分重要的。
nodejs 解决方案
原生number类型
let anum:number = 0.1
let bnum:number = 0.2
let startTime = process.hrtime.bigint()
let ans:number = anum+bnum
let endTime = process.hrtime.bigint()
console.log(`结果:${ans}\n计算用时:${endTime-startTime} 纳秒`)
结果:
结果:0.30000000000000004
计算用时:1000 纳秒
decimal 库解决方案
安装
npm i decimal.js
测试
import Decimal from "decimal.js";
let anum:Decimal = new Decimal(0.1)
let bnum:Decimal = new Decimal(0.2)
let startTime = process.hrtime.bigint()
let ans = Decimal.add(anum,bnum)
let endTime = process.hrtime.bigint()
console.log(ans,`计算用时:${endTime-startTime} 纳秒`)
结果
0.3 计算用时:244300 纳秒
计算耗时是原生的244.3倍,但是结果是准确的
C# 解决方案
using System.Diagnostics;
decimal a = 0.1M, b = 0.2M;
Stopwatch stopwatch = Stopwatch.StartNew();
decimal c = a*b;
stopwatch.Stop();
TimeSpan timeSpan = stopwatch.Elapsed;
Console.WriteLine($"运算部分经过了{timeSpan.TotalNanoseconds}纳秒\n结果是:{c}");
运算部分经过了38800纳秒
结果是:0.02
总结
在高精度计算中C#更快,nodejs耗时是C#的6.2倍左右,感觉拉不开差距啊