rnso
rnso

Reputation: 24593

How to get float number in Lua from IUP text entry

I am trying following simple code to get a decimal value from user:

require( "iuplua" )

t1 = iup.text{expand = "YES", padding = "10x10", alignment="ARIGHT", size="40x"}
btn = iup.button {title = "Print:", padding = "10x10", alignment="ACENTER", size="40x"}
qbtn = iup.button{title="Quit", expand = "YES", padding = "10x10", alignment="ACENTER", size="40x"}

function btn:action()
    strval1 = string.match (t1.value, "%d+")
    print (strval1)
    num = tonumber(strval1)
    print (num)
    end

function qbtn:action()
    os.exit()
    end

dlg = iup.dialog {
 iup.vbox{
    iup.hbox{
        iup.label{title="Decimal:", padding = "10x10", alignment="ALEFT", size="40x"},
        t1  },
    iup.hbox{
        btn,
        qbtn }}}

dlg:show()
iup.MainLoop() 

However, it prints out only an integer number (part before decimal- even 25.9999 prints as 25).

How can I get float or decimal value entered by user? Thanks for your help.

Upvotes: 1

Views: 257

Answers (2)

Antonio Scuri
Antonio Scuri

Reputation: 1071

Another option is to use the MASK attribute of the IupText to let the user only be able to enter numbers.

Upvotes: 1

lhf
lhf

Reputation: 72382

The problem with the code is that the pattern "%d+" in btn:action only gets the first run of digits.

You can change the pattern to handle decimal points, but it is hard to write a pattern that works in all cases, including optional sign and decimal point and scientific format.

It is best to let tonumber do its work: it will return nil if the string cannot be converted to a number.

Upvotes: 1

Related Questions