How to check if a number have integer representation - lua

How to check if a number have integer representation
number can be a float or double

In Lua 5.3+, use math.tointeger:
math.tointeger (x)
If the value x is convertible to an integer, returns that integer. Otherwise, returns nil.

Maybe check numbers for dot to see if it is a float or integer?
Then check this out...
dotchk=function(...);
local args={...}
assert(args[1],'Need argument')
local _,b=tostring(args[1]):gsub('%.','') -- Check for dot
if b>0 then
print('floating point found in:',args[1])
return true
else
print('No dot in:',args[1])
return false
end
end
Three examples...
>dotchk(math.pi)
floating point found in: 3.1415926535898
true
>dotchk(math.maxinteger)
No dot in: 9223372036854775807
false
>dotchk(math.mininteger)
No dot in: -9223372036854775808
false

Related

How to check if value is string in lua?

Hello guys i please need your help.
I have values, most of them are numbers but some of them are strings.
How can i check if value is string or number?
I already tried this code but when it reach string value i get error " attempt to perform arithmetic on local 'numberValue' (a nil value)"
function Config:IsNumber(value)
if value ~=nill or value ~=nil then
local numberValue = tonumber(value)
if numberValue/numberValue ==1 then
return true
else
return false
end
end
end
end
end
First of all let's start with errors in your code.
You have 2 ends to many.
it is nil, not nill. I'm not sure where you're going with that check.
Other issues / things to improve:
numberValue / numberValue == 1 does not make any sense. A number dividided by itself always results in 1. So checking that is pointless.
Also instead of
if something == 1 then
return true
else
return false
end
Can simply be replaced by return something == 1. There is no need for a conditional statement here.
To your question:
To check wether a value is a string use type(value) == "string".
To check wether a value can be convertet do a number use tonumber(value). It will either return a number or nil.
So according to your error the conversion to a number failed.
If you don't know for sure that your value can be converted to a number, you should ensure that tonumber succeded befor you do any operations on its return value.
local numberValue = tonumber(value)
if not numberValue then
print("converting value to a number failed)
return
end
-- at this point you know numberValue is a number
So if you wanted to write a function that ensures a string represents a number you could do something like this:
function IsNumber(value)
return tonumber(value) and true or false
end

How to check only numbers in value - Lua

I want to make sure players can't put letters or symbols in the value, how do I check if it is a number only?
function seed1()
ESX.UI.Menu.CloseAll()
ESX.UI.Menu.Open('dialog', GetCurrentResourceName(), 'amountseed1', {
title = 'Shop'
}, function(data, menu)
local amount = tostring(data.value)
if amount == nil then
...
else
[[What should i put here to check its only contain number ?]]
end
end, function(data, menu)
menu.close()
end)
end
I can put something like this, but maybe this isn't a good way to do that:
else
if amount > 0 and amount < 9999 then
...
else
print('Invalid amount or amount higher than 9999')
end
end
Since you only care about the number, there is no need to convert the value to string:
local amount = tostring(data.value)
-- ^^^^^^^^ partially useless
Instead, go for the number right away:
local amount = tonumber(data.value)
if amount == nil then
-- Not a number
else
-- A number
end
In the end, remember that tonumber attempts to convert the value to a number and returns nil in case of a failure.
Simply replace tostring with tonumber. This will turn strings into numbers if possible, and return nil if it can't.
Keep in mind: tonumber won't just take the largest valid prefix of a string, so tonumber("20 foo") will return nil and not 20. It also supports all ways to write number literals in Lua, so tonumber("2.3e2") will return 230 and tonumber("0xff") will return 255.

Inconsistent conversion of Float into Decimal in Ruby

First, take a specific float f:
f = [64.4, 73.60, 77.90, 87.40, 95.40].sample # take any one of these special Floats
f.to_d.class == (1.to_d * f).class # => true (BigDecimal)
So multiplying by BigDecimal casts f to BigDecimal. Therefore 1.to_d * f (or f * 1.to_d) can be seen as a (poor, but still) form of converting f to BigDecimal. And yet for these specific values we have:
f.to_d == 1.to_d * f # => false (?!)
Isn't this a bug? I'd assume that while multiplying by 1.to_d Ruby should invoke f.to_d internally. But the results differ, i.e. for f = 64.4:
f.to_d # => #<BigDecimal:7f8202038280,'0.644E2',18(36)>
1.to_d * f # => #<BigDecimal:7f82019c1208,'0.6440000000 000001E2',27(45)>
I cannot see why floating-point representation error should be an excuse here, yet it's obviously a cause, somehow. So why is this happening?
PS. I wrote a snippet of code playing around with this issue:
https://github.com/Swarzkopf314/ruby_wtf/blob/master/multiplication_by_unit.rb
So why is this happening?
TL;DR different precisions are used.
Long answer:
64.4.to_d calls bigdecimal/util's Float#to_d:
def to_d(precision=nil)
BigDecimal(self, precision || Float::DIG)
end
Unless specified, it uses an implicit precision of Float::DIG which is 15 for current implementations:
Float::DIG
#=> 15
So 64.4.to_d is equivalent to:
BigDecimal(64.4, Float::DIG)
#=> #<BigDecimal:7fd7cc0aa838,'0.644E2',18(36)>
BigDecimal#* on the other hand converts a given float argument via:
if (RB_TYPE_P(r, T_FLOAT)) {
b = GetVpValueWithPrec(r, DBL_DIG+1, 1);
}
DBL_DIG is the C-equivalent of Float::DIG, so it's basically:
BigDecimal(64.4, Float::DIG + 1)
#=> #<BigDecimal:7fd7cc098408,'0.6440000000 000001E2',27(36)>
That said, you can get the expected result if you provide the precision explicitly, either:
f.to_d(16) == 1.to_d * f
#=> true
or:
f.to_d == 1.to_d.mult(f, 15)
#=> true
and of course by explicitly converting f via to_d:
f.to_d == 1.to_d * f.to_d
#=> true
Isn't this a bug?
It looks like one, you should file a bug report.
Note that neither 0.644E2, nor 0.6440000000000001E2 is an exact representation of the given floating point number. As already noted by Eli Sadoff, 64.4's exact value is 64.400000000000005684341886080801486968994140625, so the most exact BigDecimal representation would be:
BigDecimal('64.400000000000005684341886080801486968994140625')
#=> #<BigDecimal:7fd7cc04a0c8,'0.6440000000 0000005684 3418860808 0148696899 4140625E2',54(63)>
IMO, 64.4.to_d should return just that.
This is not a bug. f == f.to_d returns false, so if f == 1.to_d * f is true, then f.to_d == 1.to_d * f must be false because f != f.to_d. The == method for BigDecimal is intended to compare BigDecimals not BigDecimal to float. Sometimes the equality will work, but for some fs the BigDecimal representation is exact whereas the float is not.
Edit: See Is Floating Point Math Broken for more of an explanation.

Value can't be assigned to a host variable because it's not in range data type

CREATE PROCEDURE ADMINIST.STUDENT_CUSTOM_PROCEDURE1 (
IN p_id INTEGER,
IN p_maths INTEGER,
IN p_science INTEGER,
Out p_obtain_marks INTEGER,
out p_percentage decimal(3,2),
out p_status char(4)
)
P1: BEGIN
DECLARE p_total INTEGER;
SET p_total = 200;
SET p_obtain_marks = p_maths + p_science;
SET p_percentage = ((p_obtain_marks * 100)/p_total);
IF (p_percentage > 35) THEN
SET p_status = 'PASS';
ELSE
SET p_status = 'FAIL';
END IF;
insert into ADMINIST.STUDENT_RESULT values(p_id, p_maths, p_science, p_obtain_marks, p_percentage, p_status);
END P1
I got Error code:
SQLCODE=-304, SQLSTATE=22003
The DEC/DECIMAL data type is different than assumed. The data type information can be found in the DB2 manual under CREATE TABLE:
"DECIMAL(precision-integer, scale-integer) or DEC(precision-integer, scale-integer)
For a decimal number. The first integer is the precision of the number; that is, the total number of digits; it may range from 1 to 31. The second integer is the scale of the number; that is, the number of digits to the right of the decimal point; it may range from 0 to the precision of the number.
If precision and scale are not specified, the default values of 5,0 are used. The words NUMERIC and NUM can be used as synonyms for DECIMAL and DEC."
So in your case, to hold percentages, change the variable declaration:
out p_percentage decimal(5,2),
I got this answer by casting value into dacimal.
SET p_percentage = DECIMAL(((p_obtain_marks * 100)/p_total),3,2);
Thanks Henrik Loeser and Alex.

Lua Problems with Arguments

What's wrong with this lua code, my argument is never converted to a number or recognized as a number no matter what I type?
I tried "distance = tonumber(arg[0]) or 0" as well.
--Args
local args = {...}
--Variables
local distance = 0
if #args > 0 and type(args[0])=="string" then args[0] = tonumber(args[0]) end
if #args > 0 and type(args[0])=="number" then distance = args[0] end
print("Distance: "..distance)
Lua uses 1-based indices for its arrays. args[0] is nil, and therefore has the type "nil".
By the way, this condition is entirely unnecessary. tonumber will check to see if its argument is a number and simply return it if needed. It will return nil if the argument cannot be converted to a number. So just use:
distance = tonumber(args[1])
You don't even need to check the length of args; if no arguments were provided, it will be nil, and tonumber will return nil. Thus, just check to see if distance is nil.

Resources