0

对于超大数 1 后 N 个 0 的整数的加减乘除,node 是否真的没办法了? 我尝试了好几个库...

 1 year ago
source link: https://www.v2ex.com/t/881017
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

V2EX  ›  问与答

对于超大数 1 后 N 个 0 的整数的加减乘除,node 是否真的没办法了? 我尝试了好几个库最后都转成科学计数法了, 而 Python 就尼玛离谱, 原生支持

  retrocode · 2 小时 40 分钟前 · 271 次点击

我找了好几个 node 库, 最后计算结果都会转成科学计数法丢失精度

类似如下计算

num = 35254311220000000000123400000004321432143543653465436534954325542098787651432
num = num - 1
print(num)

而 node 就不行, 是否真的无解了? 我目前仅需要对数字做加减乘除取余计算, 有什么解决办法吗?

10 条回复    2022-09-18 16:37:24 +08:00
retrocode

retrocode      2 小时 39 分钟前

一个玩具小项目, 感觉为了计算整个接口没必要, 所以我想尽量在前端解决问题, 结果啪撞坑上了
ljsh093

ljsh093      2 小时 36 分钟前

转字符串切一下?
wiix

wiix      2 小时 34 分钟前

自己做个大数运算库就行了,加减乘除还是很简单的。
用数组,按位存储。
Cbdy

Cbdy      2 小时 32 分钟前

35254311220000000000123400000004321432143543653465436534954325542098787651432n - 1n

用 BigInt
8520ccc

8520ccc      2 小时 30 分钟前 via iPhone

decimal 就可以

大数不可能直接用 js 的 number 来表示(只能用 string 才能完全表达)
misdake

misdake      2 小时 30 分钟前

原生就有 BigInt 啊
retrocode

retrocode      1 小时 48 分钟前

@Cbdy #4 bigint 不行 在乘除时会有丢失精度的问题 10n / 3n = 3n
@misdake #7 bigint 不行 在乘除时会有丢失精度的问题 10n / 3n = 3n
@ruxuan1306 #5 这个库似乎可以, 我研究下, 我之前试了 numjs 和 mathjs 都会转换成科学计数法
lmshl

lmshl      14 分钟前

乘除不丢失精度,你是想要 SymPy 那样的符号计算?
BrettD

BrettD      4 分钟前 via iPhone

高精度浮点数的库也有很多

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK