diff --git a/README.md b/README.md index b5698b9..32dae4b 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/ruby/split-a-float-into-its-integer-and-decimal.md b/ruby/split-a-float-into-its-integer-and-decimal.md new file mode 100644 index 0000000..1582862 --- /dev/null +++ b/ruby/split-a-float-into-its-integer-and-decimal.md @@ -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)