CPCWiki forum

General Category => Programming => Topic started by: abalore on 22:48, 01 March 24

Title: Number to string conversion in BASIC
Post by: abalore on 22:48, 01 March 24
Does anyone know how to convert a number to string in BASIC without adding spaces or other symbols?
Title: Re: Number to string conversion in BASIC
Post by: andycadley on 00:00, 02 March 24
If it's just to print it out, PRINT USING, otherwise can't it be done with STR$ or have I forgotten some subtlety?
Title: Re: Number to string conversion in BASIC
Post by: MoteroV4 on 00:20, 02 March 24
This would be an approximation:
10 n=-1
20 a$=STR$(n)
30 b$=LEFT$(a$,1)
40 IF b$=" " OR b$="-" THEN a$=RIGHT$(a$,LEN(a$)-1)
50 PRINT a$
Title: Re: Number to string conversion in BASIC
Post by: ZorrO on 03:48, 02 March 24

a$=STR$(n):a$=RIGHT$(a$,LEN(a$)-1)
Rest is not nessesery.
Title: Re: Number to string conversion in BASIC
Post by: abalore on 13:13, 02 March 24
Quote from: andycadley on 00:00, 02 March 24If it's just to print it out, PRINT USING, otherwise can't it be done with STR$ or have I forgotten some subtlety?
USING adds a % character when the digits are more than the template and spaces when less. And STR$ adds a space at the beginning.
Title: Re: Number to string conversion in BASIC
Post by: abalore on 13:16, 02 March 24
Quote from: ZorrO on 03:48, 02 March 24a$=STR$(n):a$=RIGHT$(a$,LEN(a$)-1)
Rest is not nessesery.
This is the best way so far and what I'm doing now. My question was specifically if it can be done in a single command. But it looks it's not. Weird because with HEX$ it does well. I don't understand why STR$ adds a space at the beginning, but well, I'll have to stick to the long solution.
Title: Re: Number to string conversion in BASIC
Post by: Urusergi on 15:18, 02 March 24
Quote from: abalore on 13:16, 02 March 24This is the best way so far and what I'm doing now. My question was specifically if it can be done in a single command. But it looks it's not. Weird because with HEX$ it does well. I don't understand why STR$ adds a space at the beginning, but well, I'll have to stick to the long solution.

I think it's a space reserved for the negative symbol (the positive symbol is always hidden?)
Title: Re: Number to string conversion in BASIC
Post by: abalore on 15:38, 02 March 24
@TotO proposed an even simpler solution, because I need only for positive numbers:

n$=MID$(STR$(n),2)

because the third parameter in MID$ is optional and when omitted it means "to the end of the string"
Powered by SMFPacks Menu Editor Mod