Number() 函数通过将字符串转换为数字来将数字结果加 1 [重复]

问题描述 投票:0回答:1

当我意识到输出是加一时,我想借助 '9333852702227987' 函数将

string
Number() 转换为
number

我尝试使用其他

methods
将包含上述数字的
string value
转换为
number value
,但我仍然面临同样的问题。

let convertToString = function (num1) {
    console.log(Number(num1))
    console.log(parseInt(num1))
    console.log(num1 * 1)
    console.log(Math.round(num1))
    console.log(Math.floor(num1))
    console.log(Math.ceil(num1))
    console.log('All results of the ways to convert a string into a number are wrong!!!')
};

convertToString('9333852702227987')


// The result of all of them is: 9333852702227988

你知道这是什么原因吗?

javascript string-formatting
1个回答
1
投票

这个怎么样?

const largeNumberString = '9333852702227987';
const largeNumber = BigInt(largeNumberString);

const result = largeNumber + BigInt(3);

console.log(result==9333852702227990);

在javascript中,

9333852702227987
不能被视为
Int
,因此为了解决这个问题,我们可以使用
BigInt

© www.soinside.com 2019 - 2024. All rights reserved.