Reputation: 460
If I have, say, 8.1
saved as a string/plaintext, how can I change that into the integer (that I can do addition with) 81
? (I've got to remove the period and change it into an integer. I can't seem to figure it out even though I know it should be simple. Everything I try simply outputs 1
.)
Upvotes: 2
Views: 16494
Reputation: 629
Since php does auto-casting, this should work:
<?php
$str="8432.145522";
$val = str_replace('.','', $str);
print $str." : ".$val;
?>
Output:
8432.145522 : 8432145522
Upvotes: 1
Reputation: 146191
You can also try this
$str = '8.1';
$int = filter_var($str, FILTER_SANITIZE_NUMBER_INT);
echo $int; // 81
echo $int+1; // 82
Upvotes: 5
Reputation: 9025
If you're dealing with whole numbers (as you said), you could use the intval
function that is built into PHP.
http://php.net/manual/en/function.intval.php
So basically, once you have your string parsed and setup as a whole number you can do something like:
intval("81");
And get back the integer 81.
Example:
$strNum = "81";
$intNum = intval($strNum);
echo $intNum;
// "81"
echo getType($intNum);
// "integer"
Upvotes: 2
Reputation: 16
Not sure if this will work. But if you always have something.something,(like 1.1 or 4.2), you can multiply by 10 and do intval('string here'). But if you have something.somethingsomething or with more somethings(like 1.42 and 5.234267, etc.), I don't know what to say. Maybe a function to keep multiplying by ten until it's an integer with is_int()?
Sources:
Upvotes: 0