Flurite
|
  |
| Joined: 03 Apr 2011 |
| Total Posts: 5386 |
|
|
| 22 Dec 2011 06:12 PM |
Is this a good, efficient way to check if a number is an integer or decimal?
function IntOrDec(num) if string.match(tostring(num), "%p") then return "decimal" else return "integer" end end |
|
|
| Report Abuse |
|
|
Flurite
|
  |
| Joined: 03 Apr 2011 |
| Total Posts: 5386 |
|
|
| 22 Dec 2011 06:13 PM |
| Sorry, I meant integer or* decimal. |
|
|
| Report Abuse |
|
|
|
| 22 Dec 2011 08:47 PM |
function IsInteger(num) -- bool IsInteger(number num) assert(tonumber(num), "bad argument #1 to 'IsInteger' (number expected, got " .. type(num) .. ")") return num % 1 == 0 end
In fact, you don't even need a function for it, using a function would be stupid. Just use this:
num % 1 == 0
It will return whether 'num' is an integer or not, as a boolean. |
|
|
| Report Abuse |
|
|
booing
|
  |
| Joined: 04 May 2009 |
| Total Posts: 6594 |
|
|
| 23 Dec 2011 11:16 AM |
function isInt(x) return math.floor(x) == x end troll?
~imapotato. |
|
|
| Report Abuse |
|
|
booing
|
  |
| Joined: 04 May 2009 |
| Total Posts: 6594 |
|
|
| 23 Dec 2011 11:19 AM |
function DecOrInt(x) return math.floor(x) == x and "integer" or "decimal" end Happeh?
~imapotato. |
|
|
| Report Abuse |
|
|
Legend26
|
  |
| Joined: 08 Sep 2008 |
| Total Posts: 10586 |
|
|
| 23 Dec 2011 11:22 AM |
| Using Juliens code is much faster than using math.floor or string patterns. |
|
|
| Report Abuse |
|
|
Oysi
|
  |
| Joined: 06 Jul 2009 |
| Total Posts: 9058 |
|
| |
|
Legend26
|
  |
| Joined: 08 Sep 2008 |
| Total Posts: 10586 |
|
|
| 23 Dec 2011 11:39 AM |
| I meant without the assert. Yea, it does. |
|
|
| Report Abuse |
|
|