首页 > 解决方案 > 如何在nodeJS中反转具有科学计数法的数值?

问题描述

我想了解在 NodeJS 12 中反转整数(正数和负数)的最佳方法。我们可以在不将数字转换为字符串的情况下做到这一点吗?它还应该支持科学计数法数字,例如 1e+10,即 10000000000。

Input/Expected Output
 
500 = 5
-94 = -49
1234 = 4321
-1 = -1
1e+10 = 1
123.45e+10 = 54321

标签: javascriptnode.js

解决方案


我希望这一行功能可以解决您的用例

// 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));


推荐阅读