php阅读number_format函数的源码分享
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了php阅读number_format函数的源码分享,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2816字,纯文字阅读大概需要5分钟。
内容图文
![php阅读number_format函数的源码分享](/upload/InfoBanner/zyjiaocheng/142/47a9d1f0ef1a4155af3abf4a7aec97b2.jpg)
函数原型
string number_format ( float $number [, int $decimals = 0 ] ) string number_format ( float $number , int $decimals = 0 , string $dec_point = "." , string $thousands_sep = "," )
函数可以接受1、2、4个参数(具体可以看代码的实现)。
如果只提供第一个参数,number的小数部分会被去掉,并且每个千位分隔符都是英文小写逗号"," ;
如果提供两个参数,number将保留小数点后的位数到你设定的值,其余同楼上;
如果提供了四个参数,number 将保留decimals个长度的小数部分, 小数点被替换为dec_point,千位分隔符替换为thousands_sep
PHP_FUNCTION(number_format)
// number // 你要格式化的数字 // num_decimal_places // 要保留的小数位数 // dec_separator // 指定小数点显示的字符 // thousands_separator // 指定千位分隔符显示的字符 /* {{{ proto string number_format(float number [, int num_decimal_places [, string dec_separator, string thousands_separator]]) Formats a number with grouped thousands */ PHP_FUNCTION(number_format) { // 期望number_format的第一个参数num是double类型的,在词法阶段已经对字面量常量做了转换 double num; zend_long dec = 0; char *thousand_sep = NULL, *dec_point = NULL; char thousand_sep_chr = ',', dec_point_chr = '.'; size_t thousand_sep_len = 0, dec_point_len = 0; // 解析参数 ZEND_PARSE_PARAMETERS_START(1, 4) Z_PARAM_DOUBLE(num)// 拿到double类型的num Z_PARAM_OPTIONAL Z_PARAM_LONG(dec) Z_PARAM_STRING_EX(dec_point, dec_point_len, 1, 0) Z_PARAM_STRING_EX(thousand_sep, thousand_sep_len, 1, 0) ZEND_PARSE_PARAMETERS_END(); switch(ZEND_NUM_ARGS()) { case 1: RETURN_STR(_php_math_number_format(num, 0, dec_point_chr, thousand_sep_chr)); break; case 2: RETURN_STR(_php_math_number_format(num, (int)dec, dec_point_chr, thousand_sep_chr)); break; case 4: if (dec_point == NULL) { dec_point = &dec_point_chr; dec_point_len = 1; } if (thousand_sep == NULL) { thousand_sep = &thousand_sep_chr; thousand_sep_len = 1; } // _php_math_number_format_ex // 真正处理的函数,在本文件第1107行 RETVAL_STR(_php_math_number_format_ex(num, (int)dec, dec_point, dec_point_len, thousand_sep, thousand_sep_len)); break; default: WRONG_PARAM_COUNT; } } /* }}} */
代码执行流程图
_php_math_number_format_ex
函数实现的各种参数数量,最终都会调用_php_math_number_format_ex函数。函数主要做的是:
处理负数;
根据要保留的小数点对浮点数进行四舍五入;
调用strpprintf函数将浮点数表达式转成字符串表示;
计算需要分配给结果变量的字符串长度;
将结果拷贝到返回值中(如果有千位符,则进行千位符分割)
strpprintf
这个函数是实现浮点数与字符串的转换,如上文所说,最终是调用了php_conv_fp函数做的转换(这里是通过gdb调试做的定位),而php_conv_fp函数,往下追踪,调用的是zend_dtoa函数,
更多细节注解,见github项目提交记录。
总结
阅读完这个函数的源码,学习到的是浮动数与字符串的互相转换的实现细节,字符串与浮点数之间的关系较复杂,之后还要继续学习。
以上就是php阅读number_format函数的源码分享的详细内容,更多请关注Gxl网其它相关文章!
内容总结
以上是互联网集市为您收集整理的php阅读number_format函数的源码分享全部内容,希望文章能够帮你解决php阅读number_format函数的源码分享所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。