diff --git a/README.md b/README.md index 74da020..9dd1611 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ and pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_872 TILs and counting..._ +_873 TILs and counting..._ --- @@ -539,6 +539,7 @@ _872 TILs and counting..._ - [Remove The Default Value On A Column](rails/remove-the-default-value-on-a-column.md) - [Rescue From](rails/rescue-from.md) - [Retrieve An Object If It Exists](rails/retrieve-an-object-if-it-exists.md) +- [Rounding Numbers With Precision](rails/rounding-numbers-with-precision.md) - [Secure Passwords With Rails And Bcrypt](rails/secure-passwords-with-rails-and-bcrypt.md) - [Select A Select By Selector](rails/select-a-select-by-selector.md) - [Select Value For SQL Counts](rails/select-value-for-sql-counts.md) diff --git a/rails/rounding-numbers-with-precision.md b/rails/rounding-numbers-with-precision.md new file mode 100644 index 0000000..1710397 --- /dev/null +++ b/rails/rounding-numbers-with-precision.md @@ -0,0 +1,38 @@ +# Rounding Numbers With Precision + +Ruby's `Float#round` method gets the job done, but doesn't offer much +configurability. If you'd like to finely control how a rounded number will +display, `ActiveSupport::NumberHelper` offers +[`number_to_rounded`](https://api.rubyonrails.org/classes/ActiveSupport/NumberHelper.html#method-i-number_to_rounded). + +When a precision is specified, it will apply to the fraction digits: + +```ruby +> ActiveSupport::NumberHelper.number_to_rounded(1.0, precision: 2) +=> "1.00" +``` + +Unless you include `significant: true` in which case precision will refer to +the number of signficant digits: + +```ruby +> ActiveSupport::NumberHelper.number_to_rounded(1.0, precision: 2, significant: true) +=> "1.0" +``` + +Because this is for display purposes, the return value is a string. You can +further specify that insignificant zeros are stripped from the result: + +```ruby +> ActiveSupport::NumberHelper.number_to_rounded(1.0, precision: 2, significant: true, strip_insignificant_zeros: true) +=> "1" +``` + +And for completeness, here is an example of a number being rounded up: + +```ruby +> ActiveSupport::NumberHelper.number_to_rounded(1.29, precision: 2, significant: true) +=> "1.3" +``` + +[source](https://api.rubyonrails.org/classes/ActiveSupport/NumberHelper.html#method-i-number_to_rounded)