如何强制浮点以全精度显示,不使用科学符号,而不是字符串



在Ruby中,如何在没有科学符号的情况下强制浮点显示所有有效位/全精度?

目前,我将BigDecimal转换为Float,BigDecimal(0.000000001453).to_f,但这会产生1.453e-09的结果Float。如果我做类似"%14.12f" % BigDecimal("0.000000001453").to_f的事情,我会得到一个字符串。然而,在这种情况下,作为输出的字符串是不可接受的,因为我需要它作为一个没有科学符号的实际数字浮点。

---编辑---

好的,让我在这里给出一些上下文,这可能需要改变我原来的问题。

我正试图用Highstock&lazy_high_chart。今天早些时候,当浮子以全精度浮子的形式发射到结果js时,我能够很好地绘制图形,而不是以科学符号显示。因此,我觉得问题在于这个问题。

但在我得到了一些信息之后,也许我需要对来源进行进一步的审查,我的假设是错误的。我让你决定:

@h = LazyHighCharts::HighChart.new('graph') do |f|
  hours_of_readings = 1
  reading_intervals = 1 #hour
  readings_per_hour = 60
  readings = ModelName.order("date DESC").select('data_readings.data2, data_readings.data1, data_readings.date').limit(hours_of_readings * readings_per_hour).all
  data1_and_date_series = Array.new
  data2_and_date_series = Array.new
  dates = Array.new
  # I have been thinking that the problem lies here in the "row.data1.to_f" and
  #   "row.data2.to_f" and thus this is the root of my initial question in terms 
  #   of it emitting scientific notation to the js output in the format of:
  #   [[1.0e-09], [1.04e-09],[9.4e-09], ... [3.68e-09]]
  data1_and_date_series = readings.map{|row| [(row.date.to_i * 1000), (row.data1.to_f if BigDecimal(row.data1) != BigDecimal("-1000.0"))] }
  data2_and_date_series = readings.map{|row| [(row.date.to_i * 1000), (row.data2.to_f if BigDecimal(row.data2) != BigDecimal("-1000.0"))] }

  f.series(
      :name => 'Data1',
      :data => data1_and_date_series,
      :pointStart => Time.now.to_i * 1000,
      :pointEnd => hours_of_readings.hours.ago.to_i * 1000,
      :pointInterval => reading_intervals.hour * 1000,
      :color => 'blue'
  )
  f.series(
      :name => 'Data2)',
      :data => data2_and_date_series,
      :pointStart => Time.now.to_i * 1000,
      :pointEnd => hours_of_readings.hours.ago.to_i * 1000,
      :pointInterval => reading_intervals.hour.to_i * 1000,
      :color => 'red'
  )
  f.chart({:defaultSeriesType=>"spline" })
  f.yAxis [
        {:title => { :text => "Label 1", :margin => 10} },
        {:title => { :text => "Label 2 (groups)"}, :opposite => true},
        {:max => 0},
        {:min => -0.000000001}
  ]
  f.options[:xAxis] = {
      :title => { :text => "Time"},
      :type => "datetime"
  }
  f.title(:text => "Title")
  f.legend(:align => 'right', :verticalAlign => 'top', :y => 75, :x => -50, :layout => 'vertical') # override the default values
end

这对你有用吗-

>> 0.000000001453
=> 1.453e-09 # what you are getting right now
>> puts "%1.12f" % 0.000000001453
0.000000001453 # what you need
=> nil

浮点数的字符串表示和实际值是两回事。

你在屏幕上看到的总是字符串表示,无论是科学表示法还是"正常"表示法。浮点值由to_sputs"%.10f" %等转换为其字符串表示。

浮点值本身与此无关。所以你的最后一句话没有多大意义。输出始终是一个字符串。

要在Rails的to_json中强制执行某个浮动格式,可以覆盖Float#encode_json,例如

class ::Float
  def encode_json(opts = nil)
    "%.10f" % self
  end
end

把这个放在上面的代码之前。请注意,根据您的实际值,您可能需要更复杂的逻辑来生成合理的字符串。

最新更新