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

Thoughts on Class variable for default truncation #8

Closed
n-at-han-k opened this issue Feb 11, 2024 · 2 comments
Closed

Thoughts on Class variable for default truncation #8

n-at-han-k opened this issue Feb 11, 2024 · 2 comments

Comments

@n-at-han-k
Copy link

n-at-han-k commented Feb 11, 2024

Adding .truncate(2) after every call to Percentage.new when displaying the information in a table is rather tedious.

What are your thoughts on having an option to set truncation for future calls?
Something like the following would be nice and easy to implement.

Percentage.default_truncation = 2
Percentage.new(Rational(1,3)).to_s
# => 0.33%

When working with rails you could then create an initialiser app/config/initializers/percentage.rb to set this globally.

# app/config/initializers/percentage.rb
Percentage.default_truncation = 2
@timcraft
Copy link
Member

timcraft commented Mar 6, 2024

I don't think having global options/config is appropriate for this gem.

If you want to standardise on the number of digits throughout your application you can use a helper. For example:

<%= percentage_format @change %>

That's the exact same approach as if you were using another numeric class like BigDecimal or Rational, or some other datatype where you need more than the implicit #to_s can provide (date, time, money etc).

You can also use the Rails helper, although it's more verbose:

<%= number_to_percentage(@change.to_d, precision: 1) %>

Another alternative when you're generating tables would be to use some kind of table abstraction that can format values based on their type.

@timcraft timcraft closed this as completed Mar 6, 2024
@n-at-han-k
Copy link
Author

Good idea, I like it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants