[英]PHP Validate Cost Amount 2 Decimal Places
My api requires all data related to subscription costs be in the correct format before being committed to the DB as customers will be charged the amount.我的 api 要求所有与订阅成本相关的数据在提交到数据库之前采用正确的格式,因为客户将被收取费用。 The following rules apply.
以下规则适用。
is_string($data['cost'])
is_string($data['cost'])
$data['cost'] < 0
$data['cost'] < 0
What would be the best way to go about validating requirement #3?验证需求#3 的最佳方法是什么?
Decided to go with something pretty straight forward.决定去做一些非常直接的事情。 If a decimal is present in the cost, check how many places to the right.
如果成本中存在小数,请检查右侧有多少位。 Otherwise commit to DB.
否则提交给数据库。
$amount = explode('.', $data['cost']);
if(isset($amount[1]) && strlen($amount[1]) > 2) {
// response
}
Use number_format()
.使用
number_format()
。 The advantage is that no matter what you get (not enough 0s or too many 0s) it will save it in the correct format优点是无论你得到什么(0 不够或 0 太多),它都会以正确的格式保存
number_format("1000000",2) // 1,000,000.00
Edit: To use this for validation,编辑:要使用它进行验证,
$num = $data['cost'];
$check = number_format($num,2);
if ($num == $check) return true;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.