【问题标题】:Sort array of numbers in Scientific Notation以科学记数法对数字数组进行排序
【发布时间】:2015-11-26 12:05:19
【问题描述】:

我想对一组数字(以科学计数法)从小到大进行排序。

这是我尝试过的(徒劳的):

require 'bigdecimal'
s = ['1.8e-101','1.3e-116', '0', '1.5e-5']
s.sort { |n| BigDecimal.new(n) }.reverse

# Results Obtained
# => [ "1.3e-116", "1.8e-101", "0", "1.5e-5" ]

# Expected Results
# => [ "0", "1.3e-116", "1.8e-101", "1.5e-5"]

【问题讨论】:

    标签: ruby sorting scientific-notation


    【解决方案1】:

    Enumerable#sort 的块预计会返回 -101。你要的是Enumerable#sort_by:

    s.sort_by { |n| BigDecimal.new(n) }
    # => ["0", "1.3e-116", "1.8e-101", "1.5e-5"]
    

    【讨论】:

    【解决方案2】:

    另一种选择是在sort 中使用BigDecimal#<=>

    s.sort { |x, y| BigDecimal(x) <=> BigDecimal(y) }
    #=> ["0", "1.3e-116", "1.8e-101", "1.5e-5"]
    

    【讨论】:

      猜你喜欢
      • 2011-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-05
      相关资源
      最近更新 更多