# Thread: Convert String to Decimal

1. ## Convert String to Decimal

How do I convert a String to a Decimal?

For example I am reading in from a file a value such as "41717". This is actually the value 417.17 (£417.17)...

How do I convert the value to a decimal?

I looked at using substr_replace and counting in from the end of the string two places i.e. -2 and inserting a period but this replaces everything after the insertion point.

Thanks.

2. This is just one method that quickly came to mind.

Code:
```\$str = "417.17";
\$parts = split('\.',\$str);
\$dec = \$parts[0];
\$dec += \$parts[1]/100;
echo \$dec;```
Basically, it cuts the \$str into two pieces, the whole number and the decimal. Then, it puts the whole number part and adds it to \$dec. At this point, it's still technically a string. You then divide the whole number part by 100, to turn it into an actual decimal number, then add it to \$dec, which gives you an actual double (decimal) number.

3. Sorry I dont think I was clear enough.

I have a string such as;

\$string = "41717";

I wish to convert that into "417.17"...

How do I insert the "."?

Thanks for your help so far samanime! Appreciate you always offering help.

4. Indeed once I have that string your method is good to seperate out the parts so thanks for that!

5. you can use regular expressions to validate the string (if you need to) and split it up, like so:
Code:
```\$string="8668";
if(preg_match("/^([0-9]*)([0-9]{2})\$/",\$string,\$matches))
{
\$pounds=\$matches[1]!=""?\$matches[1]:"0";
\$pence=\$matches[2];
\$currencyString="£".\$pounds.".".\$pence;
}
else \$currentString=null;
echo \$currencyString;```
Here I have assumed that there must be at least 2 characters (pence - pounds are optional) and if there are no pounds in the string then it sets pounds to 0.

6. Actually it would be much easier to just divide by 100, once you've checked its a valid number
Code:
```if(preg_match("/^([0-9]+)\$/",\$string,\$matches))
{
\$currencyValue=\$matches[1]/100;
\$currencyString="&#163;".\$currencyValue;
}
else \$currentString=null;
echo \$currencyString;```

7. Until and unless i know other way i would do it like this:
Code php:
```\$str = "41717";
\$str = substr(\$str, 0, strlen(\$str) - 2) . "." . substr(\$str, strlen(\$str) - 2, strlen(\$str));
echo "&pound;" . \$str;```

I don't say this is only way to do.

8. I wonder what is the problem with just dividing it with hundred, instead ?

9. Actually, yes, I misunderstood. I thought you were getting something like 411.11 from the string.

If you are getting a string like "41111", you can just divide it by 100 and get what you are looking for.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•