Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add decimal_si_to_f #43

Merged
merged 1 commit into from
Jul 3, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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