I am converting volume measures between cups and mL. The user can put in a fraction for the amount of cups, for example 3 and 1/2 cups, which would be stored as 2 variables: an Int
for the whole part and a Float
for the fraction. When converting to mL I can easily just make them both Double
s, add them, then multiply that by the conversion rate and make the final output an Int
for a close enough approximation.
The problem is converting that back to cups. I have an integer now so I can just make it a Double
and then divide it by the conversion rate (240) and get a Double
that has a fraction, the main issue is, I need that to be stored as 2 variables again, an Int
for the whole number (cups) and a Float
for the remainder.
I can't seem to find a way to get that remainder.
float newAmount = amount/240;
int cups = Math.floor(newAmount)
float fraction = newAmount % 1
How can I get that remainder (fraction) in Swift when dividing the 2 numbers? Most of the questions on this are just how to convert a Double
to an Int
, which I know how to do.
I tried running a test with the truncatingRemainder and it is completely dropping the remainder. Here is the test I ran...
let constA = 6
print(constA)
let constB:Float = 0.25
print(constB)
let currentAmount = Double(constA) + Double(constB)
print(currentAmount)
let newAmount = currentAmount * 240
print(newAmount)
let finalInt = Int(newAmount)
print(finalInt)
let conversionAmount = Double(finalInt) / 240
print("conversion: \(conversionAmount)")
let remainder = newAmount.truncatingRemainder(dividingBy: 1)
print("remainder \(remainder)")
var fraction = 0.0
if remainder > 0.0 {
if remainder <= 0.25 {
fraction = 0.25
} else if remainder <= 0.50 {
fraction = 0.50
} else {
fraction = 0.75
}
}
print(fraction)
The output of that is...
6
0.25
6.25
1500.0
1500
conversion: 6.25
remainder 0.0
0.0
For some reason the truncatingRemainder(dividingBy: 1) method is dropping the .25 out of the number completely.