Turn a float into a value between 0 and 1 (inclusive)?

Petar Petar
Tue Nov 21 09:53:33 UTC 2017


On Tuesday, 21 November 2017 at 09:21:29 UTC, Chirs Forest wrote:
> I'm interpolating some values and I need to make an 
> (elapsed_time/duration) value a float between 0 and 1 
> (inclusive of 0 and 1). The elapsed_time might be more than the 
> duration, and in some cases might be 0 or less. What's the most 
> efficient way to cap out of bounds values to 0 and 1? I can do 
> a check and cap them manually, but if I'm doing a lot of these 
> operations I'd like to pick the least resource intensive way.
>
> Also, if I wanted out of bounds values to wrap (2.5 becomes 
> 0.5) how would I get that value and also have 1.0 not give me 
> 0.0?

Is this what you're looking for:
https://www.desmos.com/calculator/8iytgsr3y3

In which case that would be simply:
T zeroToOne(T)(T val) { return val % 1; }


More information about the Digitalmars-d-learn mailing list