'How to refactor round method with 3 digits
I would like to round float numbers like this :
125.212 = 125.250
125.249 = 125.250
125.268 = 125.250
125.280 = 125.275
125.999 = 126.000
I have do a method, how can I refactor it ?
def round_km(n)
n = n * 1000
m = n % 100
if (m <= 25)
"%.3f" % ((n - m + 25) / 1000).round(3)
elsif (m <= 50)
"%.3f" % ((n - m + 50) / 1000).round(3)
elsif (m <= 75)
"%.3f" % ((n - m + 75) / 1000).round(3)
else
"%.3f" % ((n - m + 100) / 1000).round(3)
end
end
Solution 1:[1]
I found a better solution :
def round_km(n)
"%.3f" % ((n/0.250).ceil * 0.250)
end
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ben |
