1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 07:08:01 +00:00

Add Split A Float Into Its Integer And Decimal as a Ruby TIL

This commit is contained in:
jbranchaud
2022-12-05 09:59:01 -06:00
parent 16d8ad7849
commit d8c280513a
2 changed files with 31 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
_1268 TILs and counting..._ _1269 TILs and counting..._
--- ---
@@ -1084,6 +1084,7 @@ _1268 TILs and counting..._
- [Single And Double Quoted String Notation](ruby/single-and-double-quoted-string-notation.md) - [Single And Double Quoted String Notation](ruby/single-and-double-quoted-string-notation.md)
- [Skip Specific CVEs When Auditing Your Bundle](ruby/skip-specific-cves-when-auditing-your-bundle.md) - [Skip Specific CVEs When Auditing Your Bundle](ruby/skip-specific-cves-when-auditing-your-bundle.md)
- [Specify Dependencies For A Rake Task](ruby/specify-dependencies-for-a-rake-task.md) - [Specify Dependencies For A Rake Task](ruby/specify-dependencies-for-a-rake-task.md)
- [Split A Float Into Its Integer And Decimal](ruby/split-a-float-into-its-integer-and-decimal.md)
- [Squeeze Out The Extra Space](ruby/squeeze-out-the-extra-space.md) - [Squeeze Out The Extra Space](ruby/squeeze-out-the-extra-space.md)
- [String Interpolation With Instance Variables](ruby/string-interpolation-with-instance-variables.md) - [String Interpolation With Instance Variables](ruby/string-interpolation-with-instance-variables.md)
- [Summing Collections](ruby/summing-collections.md) - [Summing Collections](ruby/summing-collections.md)

View File

@@ -0,0 +1,29 @@
# Split A Float Into Its Integer And Decimal
Let's say we have a float value like `3.725`. We want to break it up into its
constituent parts -- the integer part (`3`) and the decimal part (`0.725`).
This can be done with the `divmod` method on the `Numeric` class.
```ruby
3.725.divmod(1)
=> [3, 0.7250000000000001]
```
In the general case, this method gives you the quotient and the modulus of
dividing the number by the given value. When that given value is specifically
`1`, it will give you those two parts of the float.
One place where this might be useful is when trying to convert a float
representing an amount of time into hours and minutes.
```ruby
hours = 3.725
hours_digit, percentage_minutes = hours.divmod(1)
minutes = (60 * percentage_minutes).to_i
hours_standard = "#{hours_digit}:#{minutes}"
```
[source](https://ruby-doc.org/core-2.5.3/Numeric.html#method-i-divmod)