Iuliana
Iuliana

Reputation: 41

Convert a string to number

I need help regarding the following;

I have the following script :

SETLOCAL DisableDelayedExpansion

for /f "delims=" %%a in (stores1.txt) do (

set /p stores=%%a )

stores.txt has the content like:

0010
0011
0012
etc.

The solution that I found is set /p stores=%%a

This output : 0010,0011,0012 must be passed as parameter to an sql.script:

sqlplus user/password@%database% @sqlscript.sql !stores! !data!

stores must be a numeric value, because in the .sql script a numeric value is interrogated

So the concluzion is that i need a numeric value not a string.How can I do this "conversion" ?

@echo off
setlocal enabledelayedexpansion
set stores=
PAUSE
for /f "delims=" %%a in (stores1.txt) do (
set /a stores=%%a
echo !stores!
)
pause

Upvotes: 4

Views: 33722

Answers (2)

Andriy M
Andriy M

Reputation: 77657

Basically, @Bali C is correct. Most times, any value is a string value in cmd unless the context either requires or suggests it be treated differently. In an arithmetic expression, for instance, values would be automatically converted to/viewed as numbers.

However, numbers in batch scripts can be treated in more than one way. In particular, depending on which character a number starts with, it can be treated as

  • a hexadecimal value (when it has the prefix of 0x);

  • an octal value (when starts with a 0);

  • a decimal value (in all other cases).

So, if you simply used e.g. 0010 in a context where a number was expected, the value would evaluate as 8, because 0010 is a number in octal notation to cmd and 8 is its decimal equivalent. That's what you would get, in particular, if you simply did this:

set /a stores=%%a

You could use the following simple trick to get rid of the leading 0s (and thus avoid the value's being treated as an octal):

set /a "stores=1%%a %% 10000"

Putting the 1 at the beginning turns it into a 5-digit number, and a decimal notation number too. Finding the remainder of division by 10000 gives you back just the original number but now with the leading 0s stripped off.

(Note: the actual modulo operator is %, not %%, but the character has to be doubled because of its special meaning beside the arithmetical context.)

Upvotes: 7

Bali C
Bali C

Reputation: 31221

I don't think cmd handles numbers differently to strings, unless you are doing arithmetic with them.

I'm not sure if it will make any difference but you can assign a variable a number using set /a, so try using

set /a stores=%%a

Upvotes: 1

Related Questions