jstern Posted May 11, 2010 Report Posted May 11, 2010 Hopefully a quick Q I have a string with the value "4,120.00" I'd like to convert this to a int or a float. (Im hoping without having to strip the string of its comma myself) the value is set using: $this->_value = round($value, 2); when I use $this->_value = ((float)$value); it just returns "4" (becuase of the comma). Same thing with (int). Anyone know a quick solution?
falkencreative Posted May 11, 2010 Report Posted May 11, 2010 Perhaps use str_replace() (http://php.net/manual/en/function.str-replace.php) to remove the comma from the string, and then convert it?
jstern Posted May 11, 2010 Author Report Posted May 11, 2010 yessum if (is_string($value)) { $value = (str_replace(",","",$value)); $this->_value = round($value, 2); } seems to be the fix i needed. I dont know why i was looking for something easier than this, this was pretty dang simple lol. (*is_string is only important due to various types being passed through my method.)
is_numeric Posted May 15, 2010 Report Posted May 15, 2010 cant you just cast the type to what you want $newVar = (int)$var;
falkencreative Posted May 15, 2010 Report Posted May 15, 2010 cant you just cast the type to what you want $newVar = (int)$var; Unfortunately not. It gets confused when it hits the comma, so "1,000" will turn into "1". See the first post in this thread - JStern mentioned that.
krillz Posted May 15, 2010 Report Posted May 15, 2010 cant you just cast the type to what you want $newVar = (int)$var; implicit transformation just cuts off the decimals it does not conduct a mathematical calculation to round the number to the nearest integer following the mathematical rules.
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now