Skip to content

Commit

Permalink
Accept variable number of decimals
Browse files Browse the repository at this point in the history
  • Loading branch information
sigmike committed Mar 28, 2017
1 parent 28ee9f3 commit a0488cc
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 22 deletions.
46 changes: 24 additions & 22 deletions lib/roo/excelx/cell/number.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,7 @@ def create_numeric(number)
def formatted_value
return @cell_value if Excelx::ERROR_VALUES.include?(@cell_value)

formatter = formats[@format]
formatter = formats["General"] if formatter.nil? and @format == "GENERAL"
formatter = generate_formatter(@format)
if formatter.is_a? Proc
formatter.call(@cell_value)
elsif zero_padded_number?
Expand All @@ -39,31 +38,34 @@ def formatted_value
end
end

def formats
def generate_formatter(format)
# FIXME: numbers can be other colors besides red:
# [BLACK], [BLUE], [CYAN], [GREEN], [MAGENTA], [RED], [WHITE], [YELLOW], [COLOR n]
{
'General' => '%.0f',
'0' => '%.0f',
'0.00' => '%.2f',
'0.000000' => '%.6f',
'#,##0' => number_format('%.0f'),
'#,##0.00' => number_format('%.2f'),
'0%' => proc do |number|
case format
when /^General$/i then '%.0f'
when '0' then '%.0f'
when /^0\.(0+)$/ then "%.#{$1.size}f"
when '#,##0' then number_format('%.0f')
when '#,##0.00' then number_format('%.2f')
when '0%'
proc do |number|
Kernel.format('%d%', number.to_f * 100)
end,
'0.00%' => proc do |number|
end
when '0.00%'
proc do |number|
Kernel.format('%.2f%', number.to_f * 100)
end,
'0.00E+00' => '%.2E',
'#,##0 ;(#,##0)' => number_format('%.0f', '(%.0f)'),
'#,##0 ;[Red](#,##0)' => number_format('%.0f', '[Red](%.0f)'),
'#,##0.00;(#,##0.00)' => number_format('%.2f', '(%.2f)'),
'#,##0.00;[Red](#,##0.00)' => number_format('%.2f', '[Red](%.2f)'),
end
when '0.00E+00' then '%.2E'
when '#,##0 ;(#,##0)' then number_format('%.0f', '(%.0f)')
when '#,##0 ;[Red](#,##0)' then number_format('%.0f', '[Red](%.0f)')
when '#,##0.00;(#,##0.00)' then number_format('%.2f', '(%.2f)')
when '#,##0.00;[Red](#,##0.00)' then number_format('%.2f', '[Red](%.2f)')
# FIXME: not quite sure what the format should look like in this case.
'##0.0E+0' => '%.1E',
'@' => proc { |number| number }
}
when '##0.0E+0' then '%.1E'
when '@' then proc { |number| number }
else
raise "Unknown format: #{format.inspect}"
end
end

private
Expand Down
2 changes: 2 additions & 0 deletions test/excelx/cell/test_number.rb
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ def test_formats
['GENERAL', '1042'],
['0', '1042'],
['0.00', '1042.00'],
['0.0000', '1042.0000'],
['0.000000000', '1042.000000000'],
['#,##0', '1,042'],
['#,##0.00', '1,042.00'],
['0%', '104200%'],
Expand Down

0 comments on commit a0488cc

Please sign in to comment.