最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Number converted in 1e+30 - Stack Overflow

programmeradmin0浏览0评论

How to convert 1e+30 to 1000000000000000000000000000000

I want number as it is entered by User do not convert like 1e+30.

How can achieve this? Is there any way to display actual digits after parse it to float or int?

How to convert 1e+30 to 1000000000000000000000000000000

I want number as it is entered by User do not convert like 1e+30.

How can achieve this? Is there any way to display actual digits after parse it to float or int?

Share Improve this question edited Dec 19, 2014 at 8:26 RobG 147k32 gold badges179 silver badges214 bronze badges asked Dec 19, 2014 at 8:03 SadikhasanSadikhasan 18.6k23 gold badges83 silver badges126 bronze badges 3
  • what about 1e30 ? :) – Roko C. Buljan Commented Dec 19, 2014 at 8:23
  • You do realize that javascript cannot handle numbers of 30 digits right? – Maurice Perry Commented Dec 19, 2014 at 8:30
  • @RokoC.Buljan It's my requirement to remain in actual digits. – Sadikhasan Commented Dec 19, 2014 at 8:32
Add a comment  | 

4 Answers 4

Reset to default 5

The core library doesn't give you any support for numbers that don't fit into the native number type, so you'll probably want to use a third party library to help you with large decimals.

For example, https://mikemcl.github.io/decimal.js/

new Decimal('1e+30').toFixed()
// "1000000000000000000000000000000"

You may use toLocaleString

(1000000000000000000000000000000).toLocaleString("en-US", { useGrouping: false })

You can make use of new Array() and String.replace, but it will only be in the form of String

function toNum(n) {
   var nStr = (n + ""); 
   if(nStr.indexOf(".") > -1) 
      nStr = nStr.replace(".","").replace(/\d+$/, function(m){ return --m; });
   return nStr.replace(/(\d+)e\+?(\d+)/, function(m, g1, g2){
      return g1 + new Array(+g2).join("0") + "0";
   })
}
console.log(toNum(1e+30)); // "1000000000000000000000000000000"

Now it's more robust as it doesn't fail even if a really huge number such as 12e100 which will be converted to 1.2e+101, is provided as the . is removed and the last set of digits decremented once. But still 100% accuracy can't be ensured but that is because of limitations of floatation maths in javascript.

JavaScript's Number type is based on the IEEE 754 double-precision floating-point format, which cannot accurately represent integers larger than 2e53 − 1.

For handling large integers, you should use BigInt

console.log(BigInt("1000000000000000000000000000000") // 1000000000000000000000000000000n

console.log(String(BigInt("1000000000000000000000000000000"))) // "1000000000000000000000000000000"

In the first log, n at the end indicates that it's a BigInt, nothing more

发布评论

评论列表(0)

  1. 暂无评论