Skip to content

Commit d8c2805

Browse files
committed
Add Split A Float Into Its Integer And Decimal as a Ruby TIL
1 parent 16d8ad7 commit d8c2805

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
1212

13-
_1268 TILs and counting..._
13+
_1269 TILs and counting..._
1414

1515
---
1616

@@ -1084,6 +1084,7 @@ _1268 TILs and counting..._
10841084
- [Single And Double Quoted String Notation](ruby/single-and-double-quoted-string-notation.md)
10851085
- [Skip Specific CVEs When Auditing Your Bundle](ruby/skip-specific-cves-when-auditing-your-bundle.md)
10861086
- [Specify Dependencies For A Rake Task](ruby/specify-dependencies-for-a-rake-task.md)
1087+
- [Split A Float Into Its Integer And Decimal](ruby/split-a-float-into-its-integer-and-decimal.md)
10871088
- [Squeeze Out The Extra Space](ruby/squeeze-out-the-extra-space.md)
10881089
- [String Interpolation With Instance Variables](ruby/string-interpolation-with-instance-variables.md)
10891090
- [Summing Collections](ruby/summing-collections.md)
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Split A Float Into Its Integer And Decimal
2+
3+
Let's say we have a float value like `3.725`. We want to break it up into its
4+
constituent parts -- the integer part (`3`) and the decimal part (`0.725`).
5+
6+
This can be done with the `divmod` method on the `Numeric` class.
7+
8+
```ruby
9+
3.725.divmod(1)
10+
=> [3, 0.7250000000000001]
11+
```
12+
13+
In the general case, this method gives you the quotient and the modulus of
14+
dividing the number by the given value. When that given value is specifically
15+
`1`, it will give you those two parts of the float.
16+
17+
One place where this might be useful is when trying to convert a float
18+
representing an amount of time into hours and minutes.
19+
20+
```ruby
21+
hours = 3.725
22+
23+
hours_digit, percentage_minutes = hours.divmod(1)
24+
25+
minutes = (60 * percentage_minutes).to_i
26+
hours_standard = "#{hours_digit}:#{minutes}"
27+
```
28+
29+
[source](https://ruby-doc.org/core-2.5.3/Numeric.html#method-i-divmod)

0 commit comments

Comments
 (0)