Ruby/Rails:如何用科学符号显示数字?

时间:2020-12-08 22:34:25

I figured this would be an easy one, but I can't find any information about it anywhere. Lets say a user enters 123456. I want to display this in scientific notation. So that would be 1.23456 * 10^5. I figured ruby or rails would have a helper method, like scientific_notation(123456), but I can't find anything. Is this possible?

我觉得这很简单,但是我找不到任何关于它的信息。假设用户输入123456。我想用科学的符号来表示。这是1.23456 * 10 ^ 5。我认为ruby或rails会有一个助手方法,比如scientific_notation(123456),但我什么都找不到。这是可能的吗?

And to take it a step further, what about processing the number if the user enters scientific notation? For instance, they enter 1.23456x10^6 - rails parses this and stores 123456 in the database.

更进一步说,如果用户输入了科学的符号,如何处理数字呢?例如,他们输入1.23456 x10 ^ 6 - rails解析这123456年并存储在数据库中。

I realize the second part is a long shot.

我意识到第二部分的可能性很大。

2 个解决方案

#1


5  

To convert a number into power of e we can use the % operator.

要将一个数字转换成e的幂,我们可以使用%运算符。

say x = 123456 then

假设x = 123456

"%e" %x
=> 1.234560e+05

#2


0  

To convert an Integer, Bignum or BigDecimal to a scientific number notation, you can use .to_f method.

要将整数、Bignum或BigDecimal转换为科学数字符号,可以使用.to_f方法。

Here some examples:

一些例子:

# Generate a long number
num = BigDecimal.new('123e+100')
#=> #<BigDecimal:1bca380,'0.123E1003',9(18)> 
num.to_s
#=> "123000000000000....
num.to_f
#=> 1.23e+102

# Convert BigDecimal to integer
int = num.to_i
#=> 123000000000000....
int.class
#=> Bignum
int.to_f
#=> 1.23e+102

In general using .to_f on Integer, Bignum and BigDecimal converts the number in a scientific notation if the number is very long (length > 15).

通常,在整数上使用.to_f时,如果数字很长(长度为>15),Bignum和BigDecimal会将数字转换为科学的表示法。

#1


5  

To convert a number into power of e we can use the % operator.

要将一个数字转换成e的幂,我们可以使用%运算符。

say x = 123456 then

假设x = 123456

"%e" %x
=> 1.234560e+05

#2


0  

To convert an Integer, Bignum or BigDecimal to a scientific number notation, you can use .to_f method.

要将整数、Bignum或BigDecimal转换为科学数字符号,可以使用.to_f方法。

Here some examples:

一些例子:

# Generate a long number
num = BigDecimal.new('123e+100')
#=> #<BigDecimal:1bca380,'0.123E1003',9(18)> 
num.to_s
#=> "123000000000000....
num.to_f
#=> 1.23e+102

# Convert BigDecimal to integer
int = num.to_i
#=> 123000000000000....
int.class
#=> Bignum
int.to_f
#=> 1.23e+102

In general using .to_f on Integer, Bignum and BigDecimal converts the number in a scientific notation if the number is very long (length > 15).

通常,在整数上使用.to_f时,如果数字很长(长度为>15),Bignum和BigDecimal会将数字转换为科学的表示法。