Jump to content

[SOLVED] Decimal places & currency - is Regex the answer?


Recommended Posts

Hi, Ok I am confused ;)

 

I have a form on my website that asks for the user's monthly earnings.

In theory they could enter an answer in any of the following formats:

 

I earn nothing

£1000

£1000.00

1000.00

£1,000

£1,000.00

1,000.00

1,000

1000

 

The backend server I submit this to will only accept the last answer i.e. a numeric value with no punctuation. I want to do as much correction as possible to prevent the user having to manually change it.

 

So there is a combination of things here. I was thinking of using 'round' to remove the decimal places if present and 'is_numeric' to eliminate the first answer but obviously I can't round a non numeric number so I have got into a bit of a complicated if...else mess. I was wondering if I could use regex to get rid of the comma and currency?

 

Any help or alternative suggestions welcome.

 

 

 

Excellent - thanks for the speedy response I just knew the right answer would be a lot simpler than my efforts ;)

 

But... it doesn't work with the £ symbol - I replaced it with an 'x' in the code and form and it worked fine. I also tried changing the code to £ and £ but it still doesn't like it?

 

 

it works for me.  Perhaps because I just c/p'ed it from your post.  Perhaps we are using diff char sets or something.  Try this instead:

 

$string = '£1,000.00';
$string = (int) preg_replace("/[^\d\.]/",'',$string);
echo $string;

Dunno if it's an issue or if you care or not but I thought I'd mention what that's actually doing.  It's replacing anything that's not a digit or period with '' (removing anything that's not a digit or . ), leaving 1000.00 and then forcing it to be an int (chopping off the .00).  So if someone were to put in like 1,000.43 you would get 1000.  Dunno if you care about rounding it up/down or if that's gonna be an issue or whatever.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  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.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.