From 7e5f873cde86944e08586ddcc873733420e1b0a1 Mon Sep 17 00:00:00 2001 From: cryptogopher Date: Fri, 6 Dec 2024 15:24:25 +0100 Subject: [PATCH] Change helper into BigDecimal method --- app/helpers/application_helper.rb | 24 ------------------------ app/views/units/_unit.html.erb | 2 +- lib/core_ext/big_decimal/formatting.rb | 22 ++++++++++++++++++++++ 3 files changed, 23 insertions(+), 25 deletions(-) diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index 4a92ba7..1f87cfc 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -132,28 +132,4 @@ module ApplicationHelper def disabled_attributes(disabled) disabled ? {disabled: true, aria: {disabled: true}, tabindex: -1} : {} end - - private - - # Converts value to HTML formatted scientific notation - def scientifize(d) - sign, coefficient, base, exponent = d.split - return 'NaN' unless sign - - result = (sign == -1 ? '-' : '') - unless coefficient == '1' && sign == 1 - if coefficient.length > 1 - result += coefficient.insert(1, '.') - elsif - result += coefficient - end - if exponent != 1 - result += "×" - end - end - if exponent != 1 - result += "10% d" % [exponent-1] - end - result.html_safe - end end diff --git a/app/views/units/_unit.html.erb b/app/views/units/_unit.html.erb index d1eec64..dda3faa 100644 --- a/app/views/units/_unit.html.erb +++ b/app/views/units/_unit.html.erb @@ -9,7 +9,7 @@ onclick: 'this.blur();', data: {turbo_stream: true} %> <%= unit.description %> - <%= scientifize(unit.multiplier) %> + <%= unit.multiplier.to_html %> <% if current_user.at_least(:active) %> diff --git a/lib/core_ext/big_decimal/formatting.rb b/lib/core_ext/big_decimal/formatting.rb index ed9bbce..8418326 100644 --- a/lib/core_ext/big_decimal/formatting.rb +++ b/lib/core_ext/big_decimal/formatting.rb @@ -8,6 +8,28 @@ module FixinMe (coefficient.length > 1 ? coefficient.insert(1, '.') : coefficient) + (exponent != 1 ? "e#{exponent-1}" : '') end + + # Converts value to HTML formatted scientific notation + def to_html + sign, coefficient, base, exponent = split + return 'NaN' unless sign + + result = (sign == -1 ? '-' : '') + unless coefficient == '1' && sign == 1 + if coefficient.length > 1 + result += coefficient.insert(1, '.') + elsif + result += coefficient + end + if exponent != 1 + result += "×" + end + end + if exponent != 1 + result += "10% d" % [exponent-1] + end + result.html_safe + end end end