Page 1 of 1
how to convert string to int
Posted: Fri May 01, 2009 11:50 am
by eke21
Hi, I have a php script that will get a line coming from a file. my problem is that, I have to compare the two values out of the lines. example :
line 1 --> I have 2,000 dollars.
line 4 --> my dollars = 1,000.00 only
i have to manipulate the values in the line, let's say 2000/1000 which is equal to 2.
how can i extract the numbers in the line and convert it to integer so that mathematical operations is possible?
thanks in advance!
Re: how to convert string to int
Posted: Fri May 01, 2009 12:11 pm
by user___
Use regular expressions. Converting is not a problem with Php(Like in Java/C++). Just make sure the extracted value is 0-9 and it is fine.
This is what I just made for you(It is just a start point). Assuming that cents are divided by ".":
Code: Select all
$string = "I have 2,000 dollars.";
$line = "my dollars = 1,000.00 only";
$string = round(preg_replace("/[^0-9\.]*/", "", $string), 2);
$line = round(preg_replace("/[^0-9\.]*/", "", $line), 2);
echo round($string/$line, 2);
Note: In Php 6, as far as I know it will not be the same, there will be strict data types.
Re: how to convert string to int
Posted: Fri May 01, 2009 7:25 pm
by hchsk
a simpler method to convert to an integer value after extraction using regex is:
Re: how to convert string to int
Posted: Sat May 02, 2009 5:15 am
by eke21
wow! thanks a lot user___! it works perfectly!
I have some questions mate, what if i'm only interested in the value of 2 lines :
for example line 14&16?
coz thats the line where I want to perform the mathematical computation.
my code now gets all the lines in the file, and i am having problem finding out the lines of my interest.
Thanks man!
Re: how to convert string to int
Posted: Sat May 02, 2009 6:17 pm
by McInfo
1. Watch out for this scenario:
Code: Select all
$str = 'I have 3,000 in the safe and 20 in my wallet';
$num = preg_replace('/[^0-9\.]*/', '', $str); // 300020
2. If you want to make sure you have an integer, you can use type casting.
PHP Manual:
Type Casting
Some interesting things to be aware of with type casting:
Code: Select all
echo (int) '20000.00'; // 20000
echo (int) 'a20000.00'; // 0
echo (int) '20,000.00'; // 20
echo (int) '-20,000.00'; // -20
Edit: This post was recovered from search engine cache.