Forum Moderators: coopster

Message Too Old, No Replies

casting string to float safely for SQL

this may be an easy one

         

httpwebwitch

3:10 pm on Jan 31, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I have a script... it receives a string (the price of a product) from a remote source and inserts it into a database as a FLOAT.

I can not change the incoming data, it's just a $_POST

I can not change the database

and worst of all:
I can not test this script! it's on a server working on live data - if I change and test it, it'll inject bogus data into the pool. A very Schrodingerian situation.

We've been getting errors when someone enters a non-numeric value for Price, eg "$US 9.00" or "13.00-14.00". So far we've been handling the errors by manually reentering the values.

it's gotten worse since the site has gained more popularity in Europe, and now we're seeing more prices like "95,00" and "95-" and "95,--"

I need a bulletproof method of converting all sorts of numeric and pseudonumeric strings into floats.

I'd be especially careful about strings like "10,00" and "10,000". One is $10 eurostyle, the other is $10000 britishstyle. Huge difference.

what do you think? is there a decent function for this already "out there"?

coopster

4:11 pm on Jan 31, 2008 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



I edit for numeric values at the client level with JavaScript first then again on the server side. Numbers only allowed during entry via Javascript. I use pattern matching (regular expressions) to replace non-numeric values and also to validate the numbers being submitted.