Skip to content

Commit

Permalink
Merge pull request #43 from zeari/decimal_si
Browse files Browse the repository at this point in the history
	add decimal_si_to_f
  • Loading branch information
bdunne authored Jul 3, 2017
2 parents 411b885 + fd28b8b commit b4bd8d3
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/more_core_extensions/core_ext/string.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
require 'more_core_extensions/core_ext/string/formats'
require 'more_core_extensions/core_ext/string/hex_dump'
require 'more_core_extensions/core_ext/string/iec60027_2'
require 'more_core_extensions/core_ext/string/decimal_suffix'
17 changes: 17 additions & 0 deletions lib/more_core_extensions/core_ext/string/decimal_suffix.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
module MoreCoreExtensions
module DecimalSI
DECIMAL_SUFFIXES = {"d" => 1e-1, "c" => 1e-2, "m" => 1e-3, "μ" => 1e-6, "n" => 1e-9, "p" => 1e-12, "f" => 1e-15,
"a" => 1e-18, "h" => 1e2, "k" => 1e3, "M" => 1e6, "G" => 1e9, "T" => 1e12, "P" => 1e15,
"E" => 1e18}.freeze
def decimal_si_to_f
multiplier = DECIMAL_SUFFIXES[self[-1]]
if multiplier
Float(self[0..-2]) * multiplier
else
Float(self)
end
end
end
end

String.send(:prepend, MoreCoreExtensions::DecimalSI)
21 changes: 21 additions & 0 deletions spec/core_ext/string/decimal_suffix_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
describe String do
it '#decimal_si_to_f' do
expect("1f".decimal_si_to_f).to eq(0.000_000_000_000_001)
expect("1p".decimal_si_to_f).to eq(0.000_000_000_001)
expect("1n".decimal_si_to_f).to eq(0.000_000_001)
expect("1μ".decimal_si_to_f).to eq(0.000_001)
expect("1m".decimal_si_to_f).to eq(0.001)
expect("1c".decimal_si_to_f).to eq(0.01)
expect("1d".decimal_si_to_f).to eq(0.1)
expect("1".decimal_si_to_f).to eq(1.0)
expect("1k".decimal_si_to_f).to eq(1_000.0)
expect("1M".decimal_si_to_f).to eq(1_000_000.0)
expect("1G".decimal_si_to_f).to eq(1_000_000_000.0)
expect("1T".decimal_si_to_f).to eq(1_000_000_000_000.0)
expect("1P".decimal_si_to_f).to eq(1_000_000_000_000_000.0)
expect("1E".decimal_si_to_f).to eq(1_000_000_000_000_000_000.0)

expect("1e9".decimal_si_to_f).to eq(1_000_000_000.0)
expect("1e-9".decimal_si_to_f).to eq(0.000_000_001)
end
end

0 comments on commit b4bd8d3

Please sign in to comment.