大佬教程收集整理的这篇文章主要介绍了ruby – 如何强制Float以完全精确的方式显示w / o科学记数法而不是字符串?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
目前我将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 [ {@R_531_6964@ => { :text => "Label 1",:margin => 10} },{@R_531_6964@ => { :text => "Label 2 (groups)"},:opposite => truE},{:max => 0},{:min => -0.000000001} ] f.options[:xAxis] = { @R_531_6964@ => { :text => "Time"},:type => "datetiR_478_11845@e" } f.title(:text => "title") f.legend(:align => 'right',:verticalAlign => 'top',:y => 75,:x => -50,:layout => 'vertical') # override the default values end
您在屏幕/打印输出上看到的内容始终是字符串表示,无论是科学记数法还是“普通”表示法.浮点数由to_s,puts,“%.10f”%等转换为字符串表示形式.
浮点值本身与此无关.所以你的最后一句话没有多大意义.输出始终是一个字符串.
要在Rails的to_json中强制执行某种浮动格式,您可以覆盖Float#encode_json,例如
class ::Float def encode_json(opts = nil) "%.10f" % self end end
把它放在上面的代码之前.请注意 – 根据您的实际值 – 您可能需要更复杂的逻辑来生成合理的字符串.
以上是大佬教程为你收集整理的ruby – 如何强制Float以完全精确的方式显示w / o科学记数法而不是字符串?全部内容,希望文章能够帮你解决ruby – 如何强制Float以完全精确的方式显示w / o科学记数法而不是字符串?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。