Dave Novo 51 Posted February 18, 2023 Hello, I know I can do the following to restrict the valid range of integer variables. TNBType= 1..2; Can I do something similar with floating point. For example, I want to restrict the values of a double precision variable to be between 0.0 to 1.0. I have tried the following TProbabilityValue=0.0..1.0; TProbabilityValue:double=0.0..1.0; TProbabilityValue:double=0..1; none of the above seem to work. I guess this is not possible, but I figured I would ask. Share this post Link to post
David Heffernan 2345 Posted February 18, 2023 3 minutes ago, Dave Novo said: Can I do something similar with floating point. No. No language or library support for anything like this. Share this post Link to post
David Schwartz 426 Posted February 18, 2023 There's always the InRange function https://docwiki.embarcadero.com/Libraries/Alexandria/en/System.Math.InRange function InRange(const AValue, AMin, AMax: Integer): Boolean; function InRange(const AValue, AMin, AMax: Int64): Boolean; function InRange(const AValue, AMin, AMax: UInt64): Boolean; function InRange(const AValue, AMin, AMax: Single): Boolean; function InRange(const AValue, AMin, AMax: Double): Boolean; function InRange(const AValue, AMin, AMax: Extended): Boolean; Share this post Link to post
Rollo62 536 Posted February 18, 2023 Probably you could use a class helper with specific access methods to mimick that behavior. Share this post Link to post
Der schöne Günther 316 Posted February 18, 2023 (edited) It's pretty verbose, but you can add your own struct with operator overloading (implicit assignment) that can throw an EArgumentOutOfRangeException when you try to stuff values outside of [0.0, 1.0] into it. While you're at it, you can overload the equality operator as well for just the precision you need. Or perhaps the add operator as well. So that adding 0.75 with 0.40 will result in 1.0. It depends on how you use these values. I'm sure the compiler is clever and won't even allocate more than the needed 4 bytes for the float. Edited February 18, 2023 by Der schöne Günther Share this post Link to post
Dave Novo 51 Posted February 18, 2023 Thanks for the suggestions. I was looking for compiler support instead of rolling my own, but all the suggestions above are great. Share this post Link to post