PHP 编写函数实现千位分组
这个,其实PHP还是有自带函数的,
number_format()
扩展阅读:http://www.w3school.com.cn/php/func_string_number_format.asp
不过有的时候我真的是太依赖自带函数了,可能其他语言没那么强大的函数库就死了吧,所以这里还是需要动动脑子的,正好弥补代码量不足的问题。
缺点在于:小数死……(这个缺点有空修复好了= =目前正在赶进度……)
先来核心函数
1 function format($num) {
2 $result = '';
3
4 while(strlen($num) > 3) { //当输入字符串长度大于3时
5 $result = ',' . substr($num, -3, 3) . $result;
6 $num = substr($num, 0, -3);
7 }
8
9 $result = $num . $result;
10 return $result;
11
12 }
13
使用strlen()
来判断字符串长度(因为input输出的是字符串形式)
我们这里还是使用substr()
来截取字符串
扩展阅读:http://www.php.net/substr
然后拼接。
完整版代码:
1<!DOCTYPE html>
2<html>
3<head>
4 <meta charset="utf-8">
5 <title>Number Format</title>
6</head>
7<body>
8 <form action="format.php" method="post">
9 <input type="text" placeholder="输入Number" name="number">
10 <input type="hidden" name="shot" value="shot">
11 <input type="submit" value="提交">
12 </form>
13
14 <?php
15 if(!empty($_POST['shot'])) {
16 $num = $_POST['number'];
17 $problem = FALSE;
18
19 if(!is_numeric($num)) {
20 $problem = TRUE;
21 echo "你确定你输入的数字吗";
22 }
23
24 if(!$problem) {
25 $result = format($num);
26
27 echo "转换后的数据为" .$result;
28 }
29 }
30
31 function format($num) {
32 $result = '';
33
34 while(strlen($num) > 3) { //当输入字符串长度大于3时
35 $result = ',' . substr($num, -3, 3) . $result;
36 $num = substr($num, 0, -3);
37 }
38
39 $result = $num . $result;
40 return $result;
41
42 }
43 ?>
44</body>
45</html>
46
这里我们用is_numeric()
判断是否是数字或者数字字符串(因为是字符串不能用诸如is_int
之类的)
扩展阅读:http://www.php.net/manual/zh/function.is-numeric.php
评论 (0)