File tree Expand file tree Collapse file tree 2 files changed +31
-1
lines changed Expand file tree Collapse file tree 2 files changed +31
-1
lines changed Original file line number Diff line number Diff line change @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
10
10
11
11
For a steady stream of TILs, [ sign up for my newsletter] ( https://crafty-builder-6996.ck.page/e169c61186 ) .
12
12
13
- _ 1268 TILs and counting..._
13
+ _ 1269 TILs and counting..._
14
14
15
15
---
16
16
@@ -1084,6 +1084,7 @@ _1268 TILs and counting..._
1084
1084
- [ Single And Double Quoted String Notation] ( ruby/single-and-double-quoted-string-notation.md )
1085
1085
- [ Skip Specific CVEs When Auditing Your Bundle] ( ruby/skip-specific-cves-when-auditing-your-bundle.md )
1086
1086
- [ 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 )
1087
1088
- [ Squeeze Out The Extra Space] ( ruby/squeeze-out-the-extra-space.md )
1088
1089
- [ String Interpolation With Instance Variables] ( ruby/string-interpolation-with-instance-variables.md )
1089
1090
- [ Summing Collections] ( ruby/summing-collections.md )
Original file line number Diff line number Diff line change
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 )
You can’t perform that action at this time.
0 commit comments