Splitting numbers. -
Roel - 16.05.2013
Hello,
I have to split numbers on a way like this;
When I have a number like 1223
I want to split it so I get , 122 and 3
But also when I have 32032 as number, it should become 3203 and 2.
Or 10 should become 1 and 0.
Is there a easy way to do this?
Or should i write a function for it.
Re: Splitting numbers. -
[HiC]TheKiller - 16.05.2013
I would just do it the easy way and use
Valstr. For example,
pawn Код:
new number = 1223, str[5];
valstr(str, number);
//str[0] = "1"
//str[1] = "2"
//str[2] = "2"
//str[3] = "3"
You can just use string functions to split it. May be an easier way, but that's just how I'd do it.
Re: Splitting numbers. - Emmet_ - 16.05.2013
I've written a function just now that cuts numbers in half:
pawn Код:
cut(const integer, const pos, const delim=' ', &value1, &value2) {
new str[16], splitter[2], value[2][16];
splitter[0] = delim;
format(str, 16, "%d", integer);
strins(str, splitter, pos);
strmid(value[0], str, 0, strfind(str, splitter), 16);
strmid(value[1], str, strfind(str, splitter) + 1, strlen(str), 16);
value1 = strval(value[0]);
value2 = strval(value[1]);
}
For example, my number is
35270.
pawn Код:
new num1, num2;
cut(35270, 2, ' ', num1, num2);
printf("Number 1: %d", num1);
printf("Number 2: %d", num2);
Outputs the following:
Код:
[05:06:23] 35
[05:06:23] 270
Re: Splitting numbers. -
Roel - 16.05.2013
Ow well, thanks both of you, I already wrote a function, but I will look at yours Emmet.
Anyway here is my function;
Код:
stock GetRoomInfo(roomid,type)
{
if(type == ROOM_NUMBER)
{
new number[26];
new finalnum[26];
valstr(number,roomid);
strmid(finalnum, number, strlen(number)-1, strlen(number));
return strval(finalnum);
}
if(type == ROOM_VIRTUALWORLD)
{
new number[26];
valstr(number,roomid);
strdel(number, strlen(number)-1, strlen(number));
return strval(number);
}
return 1;
}
Re: Splitting numbers. -
Vince - 16.05.2013
What? Why would it be necessary to convert it to string first and then convert it back? This solves all your problems:
pawn Код:
new LastDigit = number % 10;
Edit: To get the left part you would subtract the LastDigit from the orginal number and then divide by 10. Ex:
pawn Код:
1222 % 10 = 2
(1222 - 2) / 10 = 1220 / 10 = 122
Re: Splitting numbers. -
Roel - 16.05.2013
Yo thanks that worked great.