简体   繁体   English

PHP 验证成本金额 2 个小数位

[英]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.以下规则适用。

  1. Must be numeric with no currency symbols.必须是没有货币符号的数字。 Validating using is_string($data['cost'])使用is_string($data['cost'])
  2. Cannot be a negative amount.不能是负数。 Validating using $data['cost'] < 0使用$data['cost'] < 0
  3. Must have two decimal places, even when the amount has no cents ($100.00).必须有两位小数,即使金额没有美分 ($100.00)。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM