javascript - 如何在nodeJS中反转具有科学计数法的数值?
问题描述
我想了解在 NodeJS 12 中反转整数(正数和负数)的最佳方法。我们可以在不将数字转换为字符串的情况下做到这一点吗?它还应该支持科学计数法数字,例如 1e+10,即 10000000000。
Input/Expected Output
500 = 5
-94 = -49
1234 = 4321
-1 = -1
1e+10 = 1
123.45e+10 = 54321
解决方案
我希望这一行功能可以解决您的用例
// The Math.sign() function returns either a positive or negative +/- 1,
// indicating the sign of a number passed into the argument.
function reverseInt(n) {
return parseInt(n.toString().split('').reverse().join('')) * Math.sign(n)
}
console.log(reverseInt(500));
console.log(reverseInt(-94));
console.log(reverseInt(1234));
推荐阅读
- python - Django 将输入传递给 URL
- sql - 以 JSONB 格式更新 PostgreSQL 的对象数组
- nginx - kubernetes nginx ingress 是如何在没有特定配置的情况下选择合适的 pod 来平衡的?
- typescript - 为什么 AWS CDK Typescript 在 VPC 中创建额外的子网
- html - 是否可以传递 base64 字符串来定义 Manifest.json 中的图标?
- javascript - 如何在 jQuery 中使用 document.querySelectorAll() 来提高性能?
- python - 在 python 中,你将如何创建两个相互迭代的列?
- reactjs - React Native向PNG添加边框
- python - 如何循环一个 yaml 以创建另一个带有变量的 yaml
- javascript - 如何使用 nodemailer 和 roundcube 发送电子邮件