![]() |
|
|||||||
| 代码交流 ASP,PHP,JSP等网站源代码下载与交流。 |
![]() |
|
|
Thread Tools | Display Modes |
|
#1
IP: 222.76.215.18
|
|||
|
|||
|
数字
在处理数字时,如货币金额,实际上并没有通用的检验方式,而是要根据特定输入信息检查数据是否在有效范围之内。不过我们可以创建一个函数来标准化得到的任何数值,所使用的格式满足大多数数据库对数值格式的要求,也就是说数字之间没有空格或逗号,负数值前面会有一个负号。另外,利用可选参数指定保留的小数位,自动进行四舍五入的操作。 PHP能够根据需要自动把字符串转化为数值,但逗号、空格和其他一些因素经常会影响这种转化。程序清单11.4.1解决了这些问题,从而得到有效的数值。 程序清单11.4.1 通用数值检验函数库 <?php // A function that will accept and clean up number strings function standardize_number($num, $precision = false) { // First, remove all non-digits, periods, and - signs from the string $num = preg_replace('/[^-.0-9]/', '', $num); // Now remove any -'s that are in the middle of the string: $num = preg_replace('/(?<=.)-/', '', $num); // We now have a valid string that PHP will properly consider a number. // If a precision was asked for, round accordingly: if ($precision !== false) { $num = round($num, $precision); } return $num; } // Standardize some number strings: $nums = array('123.4643', 'Hello I bought 42 flowers for you.', '-344-345.424', '+544,342.566'); foreach ($nums as $num) { $st = standardize_number($num, 2); echo "<p>{$num} = {$st}</p>\n"; } ?> |
![]() |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| google电话验证成功的关键 | car | Google Adsense | 0 | 2007-12-16 05:44 PM |
| 用session代替apache服务器验证 | smiling | 代码交流 | 0 | 2006-12-15 07:25 PM |