From 03258b0514a3c3bf52c668322a2be80683797492 Mon Sep 17 00:00:00 2001 From: Toon Willems Date: Mon, 30 Sep 2024 15:06:33 +0200 Subject: [PATCH] format numbers with 6 significant digits --- app/views/helpers/money_helper.rb | 6 ++++++ spec/views/helpers/money_helper_spec.rb | 27 +++++++++++++++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 spec/views/helpers/money_helper_spec.rb diff --git a/app/views/helpers/money_helper.rb b/app/views/helpers/money_helper.rb index 01e55ddffbc5..eeaf37c58afb 100644 --- a/app/views/helpers/money_helper.rb +++ b/app/views/helpers/money_helper.rb @@ -10,6 +10,12 @@ def self.format(money) end def self.format_with_precision(amount_cents, currency) + amount_cents = if amount_cents < 1 + BigDecimal("%.6g" % amount_cents.frac) + else + amount_cents.round(6) + end + Utils::MoneyWithPrecision.from_amount(amount_cents, currency).format( format: I18n.t('money.format'), decimal_mark: I18n.t('money.decimal_mark'), diff --git a/spec/views/helpers/money_helper_spec.rb b/spec/views/helpers/money_helper_spec.rb new file mode 100644 index 000000000000..8575b7794d13 --- /dev/null +++ b/spec/views/helpers/money_helper_spec.rb @@ -0,0 +1,27 @@ +# frozen_string_literal: true + +require 'rails_helper' + +RSpec.describe MoneyHelper do + subject(:helper) { described_class } + + describe '.format_with_precision' do + it 'rounds big decimals to 6 digits' do + html = helper.format_with_precision(BigDecimal("123.12345678"), "USD") + + expect(html).to eq('$123.123457') + end + + it 'shows six significant digits for values < 1' do + html = helper.format_with_precision(BigDecimal("0.000000012345"), "USD") + + expect(html).to eq('$0.000000012345') + end + + it 'shows only six significant digits for values < 1' do + html = helper.format_with_precision(BigDecimal("0.100000012345"), "USD") + + expect(html).to eq('$0.10') + end + end +end