加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 如何强制Float以完全精确的方式显示w / o科学记数法而不

发布时间:2020-12-16 23:33:04 所属栏目:百科 来源:网络整理
导读:如何在没有 Ruby的科学记数法的情况下强制浮动显示所有重要位置/全精度? 目前我将BigDecimal转换为Float,BigDecimal(0.000000001453).to_f,但这会产生1.453e-09的结果浮点数.如果我做“?.12f”%BigDecimal(“0.000000001453”).to_f,我得到一个字符串.但
如何在没有 Ruby的科学记数法的情况下强制浮动显示所有重要位置/全精度?

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

—编辑—

好吧,让我在这里给出一些背景,这可能需要改变我原来的问题.

我正在尝试用Highstock& amp;创建一个图表. 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,: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

解决方法

字符串表示和float的实际值是两个不同的东西.

您在屏幕/打印输出上看到的内容始终是字符串表示,无论是科学记数法还是“普通”表示法.浮点数由to_s,puts,“%.10f”%等转换为字符串表示形式.

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

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读