如何将包含科学记数法的字符串转换为正确的 Javascript 数字格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10943997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a String containing Scientific Notation to correct Javascript number format
提问by Olga
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 Eat the end is ignored.
我有一个 String e.g: "4.874915326E7"
。将其转换为 javascript 数字格式的最佳方法是什么?(整数或浮点数)?如果我尝试 parseInt(),最后的E将被忽略。
回答by Joseph Marikle
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.
这个答案似乎引起了一些混乱。最初的问题是询问如何将字符串形式的科学记数法转换为数字(以便它可以用于计算)。但是,找到这个答案的很多人似乎认为这是将 javascript 表示为科学记数法的数字转换为更易于展示的格式。如果这实际上是您的目标(演示),那么您应该将数字转换为字符串。请注意,这意味着您将无法轻松地在计算中使用它。
Original Answer:
原答案:
Pass it as a string to the Number function.
将其作为字符串传递给 Number 函数。
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:
这是另一个问题的最佳答案,但从那个问题来看,我个人喜欢使用.toLocaleString()
. 请注意,该特定解决方案不适用于负数。为了您的方便,这里有一个例子:
(4e+27).toLocaleString('fullwide', {useGrouping:false}) // returns "4000000000000000000000000000"
回答by Yaroslav Melnichuk
You can also use +
sign in front of your string to get a number.
您还可以+
在字符串前使用符号来获取数字。
+"4.874915326E7" // == 48749153.26
回答by Matt Riedemann
I had a value like this 3.53048874968162e-09
and using Number.toFixed(20)
worked for me:
我有这样的价值,3.53048874968162e-09
并且使用Number.toFixed(20)
对我有用:
value = new Number('3.53048874968162e-09')
//[Number: 3.53048874968162e-9]
value.toFixed(20)
//'0.00000000353048874968'
回答by Oleg Valter
Preamble
前言
While other answers are sufficient and correct, to be able to correctly parse numbers from strings, it is useful to understand how type coercion (conversion in your case) works at least at high level.
虽然其他答案已经足够且正确,但为了能够正确解析字符串中的数字,了解类型强制(在您的情况下为转换)的工作方式至少在高层次上是有用的。
Coercion rules
强制规则
There are rules that define how conversion is performed when you invoke utilities like parseInt
, parseFloat
, Number
constructor or +
unary operator:
有一些规则定义了在调用parseInt
, parseFloat
,Number
构造函数或+
一元运算符等实用程序时如何执行转换:
parseInt(<value>, [radix])
function:
parseInt(<value>, [radix])
功能:
- ignores leading whitespaces (
" 24"
->24
) - empty strings return
NaN
- first non-numeric char finishes parsing (
" 42answer"
->42
) - under above rule, decimal places finish parsing as well
- 忽略前导空格 (
" 24"
->24
) - 空字符串返回
NaN
- 第一个非数字字符完成解析(
" 42answer"
->42
) - 在上述规则下,小数位也完成解析
The third rule is exactly why exponent part (ExponentPart
consists of ExponentIndicator
and SignedInteger
as defined in standard) is ignored - as soon as the e
char is encountered, parsing stops and the function returns the number parsed so far. In fact, it stops earlier - when the decimal point is first encountered (see the last rule).
第三条规则正是为什么指数部分(ExponentPart
由ExponentIndicator
和SignedInteger
定义在标准中)被忽略 - 一旦e
遇到字符,解析就会停止并且函数返回到目前为止解析的数字。事实上,它会更早停止——当第一次遇到小数点时(见最后一条规则)。
parseFloat()
is identical to parseInt
, except:
parseFloat()
与 相同parseInt
,除了:
- it parses first decimal point
- ignores leading
0
(thus hexadecimal can't be parsed)
- 它解析第一个小数点
- 忽略前导
0
(因此无法解析十六进制)
As a rule of thumb, you should use parseInt
when converting to an "integer" and parseFloat
to "float" (note that they are actually the same type).
根据经验,您应该parseInt
在转换为“整数”和parseFloat
“浮点数”时使用(注意它们实际上是相同的类型)。
Number()
constructor and unary +
:
Number()
构造函数和一元+
:
For boolean ->
true
to1
,false
to0
For
null
->0
(becausenull
is falsy)For
undefined
->NaN
For numbers: pass-through
For strings:
- only numeric [0-9] chars, starts with numeric or
+
or-
-> number (integer) - same, but contains floating-point -> number (floating-point)
- contains hexadecimal -> number (integer)
- empty string ->
0
- all other cases ->
NaN
- only numeric [0-9] chars, starts with numeric or
For objects, their
valueOf()
method is called. If result isNaN
, thentoString()
method is called. Under the hood, the object is converted to primitive and that primitive is converted to number.For symbols and BigInts ->
TypeError
is thrown
对于 boolean ->
true
to1
,false
to0
For
null
->0
(因为null
是假的)对于
undefined
->NaN
对于数字:直通
对于字符串:
- 仅数字 [0-9] 字符,以数字或
+
或-
-> 数字(整数)开头 - 相同,但包含浮点数 -> 数字(浮点数)
- 包含十六进制 -> 数字(整数)
- 空字符串 ->
0
- 所有其他情况->
NaN
- 仅数字 [0-9] 字符,以数字或
对于对象,它们的
valueOf()
方法被调用。如果 result 是NaN
,则toString()
调用方法。在幕后,对象被转换为原始对象,而原始对象被转换为数字。对于符号和 BigInts ->
TypeError
被抛出
Note on number format
数字格式注意事项
As the question still attracts answers and comments that are concerned with formatting (as validly stated by the accepted answer), it should be stated that:
由于该问题仍然吸引与格式有关的答案和评论(如已接受的答案所有效说明),因此应说明:
As applied to programming, there is a strict meaning of "number format":
representation of the numeric value"conversion"also has a strict meaning as type conversion(see standard)
应用于编程时,“数字格式”有一个严格的含义:
数值的表示“转换”作为类型转换也有严格的含义(参见标准)
ECMAScript implements double-precision 64-bit formatand that's the only "format" it has. The question asks about converting a String to number format, therefore answers are expected to provide info on:
ECMAScript 实现了双精度 64 位格式,这是它唯一的“格式”。该问题询问将 String 转换为数字格式,因此答案应提供以下信息:
How to convert String to Number given the value represents a number in e-notation
给定值表示电子符号中的数字,如何将字符串转换为数字
References
参考
ToNumber
abstract operationin ECMAScript standard- One of the best reads I had on this topic and many others: Matt Frisbie's "Professional Javascript for Web Developers".
- Type coercion explained (blog post)