Jump to content

String to float or int


jstern

Recommended Posts

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?

Link to comment
Share on other sites

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.)

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...