How can I scale a number to fit in a specified range? For example if I have:
Input_min = 10.1;
Input_max = 750.0;
Range_min = 0.0;
Range_max = 350.0;
example Input_n = 503.9;
How can I make any number to scale in the Range min and max using swift?
edit/update: Xcode 11.5 • Swift 5.2
extension FloatingPoint {
func converting(from input: ClosedRange<Self>, to output: ClosedRange<Self>) -> Self {
let x = (output.upperBound - output.lowerBound) * (self - input.lowerBound)
let y = (input.upperBound - input.lowerBound)
return x / y + output.lowerBound
}
}
extension BinaryInteger {
func converting(from input: ClosedRange<Self>, to output: ClosedRange<Self>) -> Self {
let x = (output.upperBound - output.lowerBound) * (self - input.lowerBound)
let y = (input.upperBound - input.lowerBound)
return x / y + output.lowerBound
}
}
let integer = 380
let result = integer.converting(from: 10...750, to: 100...350) // 225
let double = 750.0
let result = double.converting(from: 10.1...750.0, to: 0...350) // 350
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With