Skip to content

Commit

Permalink
format numbers with 6 significant digits
Browse files Browse the repository at this point in the history
  • Loading branch information
nudded committed Sep 30, 2024
1 parent a8c3a93 commit f168da2
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
6 changes: 6 additions & 0 deletions app/views/helpers/money_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
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'),
Expand Down
27 changes: 27 additions & 0 deletions spec/views/helpers/money_helper_spec.rb
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit f168da2

Please sign in to comment.