mirror of
https://github.com/jbranchaud/til
synced 2026-01-02 22:58:01 +00:00
Add Split A Float Into Its Integer And Decimal as a Ruby TIL
This commit is contained in:
@@ -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).
|
||||
|
||||
_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)
|
||||
- [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)
|
||||
- [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)
|
||||
- [String Interpolation With Instance Variables](ruby/string-interpolation-with-instance-variables.md)
|
||||
- [Summing Collections](ruby/summing-collections.md)
|
||||
|
||||
29
ruby/split-a-float-into-its-integer-and-decimal.md
Normal file
29
ruby/split-a-float-into-its-integer-and-decimal.md
Normal 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)
|
||||
Reference in New Issue
Block a user