当数值过大时,即便是 BigInt
也出现了精度缺失,所以就自己简单写了个方法
function toHex(n) {
base = BigInt(16)
array = []
map = {
10: 'a',
11: 'b',
12: 'c',
13: 'd',
14: 'e',
15: 'f'
}
while(n > 0){
res = n % base
n = n / base
if (res >= 10) {
res = map[res]
}
array.push(res.toString())
}
array.reverse()
return "0x"+array.join("")
}
console.log(toHex(BigInt(100)))
console.log(toHex(BigInt(200000) * BigInt(10**18)))
请注意,传入的数,也需是 BigInt