Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - `Scale Number in a Range min - max

Tags:

range

swift

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?

like image 271
SNos Avatar asked Jul 07 '15 16:07

SNos


1 Answers

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
like image 200
Leo Dabus Avatar answered Nov 15 '22 07:11

Leo Dabus