gnuforth how to convert a string containing a number to its integer part

29 Views Asked by At

I have some existing codes resulting in variables as strings some of them are currently displayed juste like

out 2@ type

This is fine, answering a string or any number like 3.666 49.888 or whatever it contains

I would convert it as an integer to the top of the stack. something like

out 2@ convert 

an optain for example 3 or 49 to keep same example

I tried some

: .$ swap over dabs  compiled             
 <# # [CHAR] . hold # # #> ;  

and so many similar string management but I always fail to get it

I can also use

out 2@ evaluate

but then I got a strange number 49888 instead of 49 ignoring the .888

I check all documentation about substring management with tools like word /string & so on but nothing about either getting a sub string from "." as separator nor string conversion to an integer of coherent value

I also tryied to check all in rosetta-code without success.

any Idea of words or procedure I would use to get the entire part of a number if this one is currently comming from a string variable ?

1

There are 1 best solutions below

0
francois P On

OK I got help from other people but it may help to post also here with a POC example

The variable muste be a 2variable state then I can capture as a string a system command or whatever I want

next step is to manage a delimiter on input address length char to get out put address new length.

then I can get from the delimiter a substring, if the string is containing a float , then with dot delimiter the substring is the entire part only. Then I can evaluate it to make it a number on top of the stack

here is the POC

\ use case test / ideas / and fix
\ help from reddit :; community
create buffer 1024 allot        \ for general purpose usage redefined buffer   
2variable out           \ general purpose output  changed to 2variable ; idea from Armok628 on redit 

: commandout ( "system" -- string ) 
    r/o open-pipe throw dup buffer swap 256 swap read-file throw  swap close-pipe throw drop buffer swap out 2! 
; 

\ random example to get a value  
s" psql -c 'select avg(prct)*100 from jx ;' | sed '3!d' " commandout  

\ here out is now containing a string like 47.456426514 or similar form

: DELIMITED ( addr len char --  addr len) 
    >R 2DUP R> SCAN NIP - \ good idea from bfox9900 reddit
;
\ this reads the delimiter & put addr+len on stack (so a string / the new string)
\ it is not yet a number

: test 
    dup             \ for tailing spaces
    ." ["
    0 DO ." #" loop
    100 swap - 0 do 32 emit loop 
    ." ]"
    cr
;
\ this test just reuse the number to verify it is a number

page \ clear screen (of the current terminal) 
out 2@ char. delimited evaluate \ here is now a number 
cr test cr \ pass number as input of test function 

bye