Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
475 views
in Technique[技术] by (71.8m points)

How to convert a String containing Scientific Notation to correct Javascript number format

I have a String e.g: "4.874915326E7". What is the best way to convert it to a javascript number format? (int or float)? if I try parseInt(), the E at the end is ignored.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Edit:

This answer seems to be generating some confusion. The original question was asking how to convert scientific notation in the form of a string to a number (so that it could be used for calculation). However, a significant number of people finding this answer seem to think it's about converting a number that is being represented by javascript as scientific notation to a more presentable format. If that is in fact your goal (presentation), then you should be converting the number to a string instead. Note that this means you will not be able to use it in calculations as easily.

Original Answer:

Pass it as a string to the Number function.

Number("4.874915326E7") // returns 48749153.26
Number("4E27") // returns 4e+27

Converting a Number in Scientific Notation to a String:

This is best answered by another question, but from that question I personally like the solution that uses .toLocaleString(). Note that that particular solution doesn't work for negative numbers. For your convenience, here is an example:

(4e+27).toLocaleString('fullwide', {useGrouping:false}) // returns "4000000000000000000000000000"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...