Skip to content

Instantly share code, notes, and snippets.

@gaqzi
Created April 18, 2011 08:38
Show Gist options
  • Save gaqzi/925007 to your computer and use it in GitHub Desktop.
Save gaqzi/925007 to your computer and use it in GitHub Desktop.
Ruby Spreadsheet, NaN is a Float but it doesn't adhere to any operations so doing multiplication on a NaN will make the script explode
--- orig/worksheet.rb 2011-04-18 10:26:50.000000000 +0200
+++ patched/worksheet.rb 2011-04-18 10:27:23.000000000 +0200
@@ -89,7 +89,7 @@
def need_number? cell
if cell.is_a?(Numeric) && cell.abs > 0x1fffffff
true
- elsif cell.is_a?(Float)
+ elsif cell.is_a?(Float) and not cell.nan?
higher = cell * 100
if higher == higher.to_i
need_number? higher.to_i
--- a/test/excel/writer/worksheet.rb
+++ b/test/excel/writer/worksheet.rb
@@ -14,6 +14,7 @@ class TestWorksheet < Test::Unit::TestCase
assert_equal false, sheet.need_number?(114.55)
assert_equal false, sheet.need_number?(0.1)
assert_equal false, sheet.need_number?(0.01)
+ assert_equal false, sheet.need_number?(0 / 0.0) # NaN
assert_equal true, sheet.need_number?(0.001)
assert_equal true, sheet.need_number?(10000000.0)
end
# Without the patch this file will not be written out because of the NaN.
# Infinity will be written out, it'll look odd but it'll be written out in the Excel file.
# So I suggest the patch so that NaN is written out the same as INF, even if neither really ought to be written to a file to begin with.
require 'rubygems'
require 'spreadsheet'
wb = Spreadsheet::Workbook.new
ws = wb.create_worksheet(:name => 'test')
ws[0,1] = 1 / 0.0 # INF
ws[0,2] = 'test'
ws[0,3] = 0 / 0.0 # NaN
wb.write('test.xls')
@zdavatz
Copy link

zdavatz commented Apr 18, 2011

Thanks for this patch!

Can you please supply us with some testcode for the according test file?

Best
Zeno

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment