PHP 将用户友好的格式化价格处理为标准浮点数
我有一个表单,用户可以在其中输入商品的价格。理想情况下,我希望用户能够以他们认为最好的任何方法添加价格,并且也为了可读性。然后,我需要将其转换为标准浮点数,以便我的网络服务可以计算成本等。
我正在努力解决的部分是如何获取货币的初始 sting/float/int 并将其转换为浮点数。
例如:
UK: 1,234.00
FRA: 1 234,00
RANDOM: 1234
RANDOM2: 1234.00
所有这些的格式都略有不同。
我想存储为:
1234.00
然后我将结果作为 DECIMAL 存储在 MySQL 数据库中。
任何帮助都会很棒。
I have a form in which users can enter prices for items. Ideally I want the user to be able to add prices in whatever method feels best to them and also for readability. I then need to convert this to a standard float so that my web service can calculate costs etc.
The part I'm struggling with is how to take the initial sting/float/int of currency and convert it into a float.
For example:
UK: 1,234.00
FRA: 1 234,00
RANDOM: 1234
RANDOM2: 1234.00
All of those have slightly different formats.
Which I would want to store as:
1234.00
I will then store the result in MySQL database as a DECIMAL.
Any help would be great.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设您使用 MySQL,则使用 DECIMAL 或 NUMERIC 类型是用于存储货币的正确类型。
浮点数容易受到舍入误差的影响并且精度有限。
显示格式应由 PHP 处理。
如果存储在数据库中,您当然应该存储一个货币代码 - 检索时可以使用它来告诉 PHP 如何显示它
Assuming you're using MySQL, use the DECIMAL or NUMERIC type are the correct types used for storing currency.
Float's are susceptible to rounding errors and have a limited precision.
The formatting for display should be handled by PHP.
If storing in DB, you should of course store a currency code - which can be used when retrieving to tell PHP how to display it
你不能使用:
Couldn't you use:
如果您想接受如此多不同的格式,那么要正确处理就有点困难了。
现在我们可以使用一个简单的正则表达式来获取值的小数部分和完整部分:
正则表达式将捕获数字的完整部分+小数部分,以 , 或 a 分隔。其中有一个或两个数字。
捕获组 1 将包含完整部分,组 2 将包含小数部分(如果有)。
要获得您的数字,您只需从完整部分中过滤掉所有非数字字符,并将过滤后的完整部分和小数部分连接在一起。
如果你想让它更加万无一失,你可能应该在客户端实现一些东西来引导用户以正确的格式输入值。
In a case where you'd like to accept so many different formats it's a bit tricky to get it right.
Now we can just use a simple regex to get the decimal and full parts of the value:
The regex will capture the full part of the number + a decimal part, separated with a , or a . and which has one or two numbers.
The capture group 1 will contain the full part, and group 2 the decimal part (if any).
To get your number, you just need to filter out all non-numeric characters from the full part, and join the filtered full and decimal parts together.
If you want to make it more foolproof, you probably should implement something on the client-side to guide the user to input the value in the correct format.