Jump to content
Stef's Coding Community
Sign in to follow this  
jstern

String to float or int

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?

Share this post


Link to post
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.)

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
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.

Share this post


Link to post
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...
Sign in to follow this  

×
×
  • Create New...