PHP printf函数和它的奇怪行为 [英] PHP printf function and it's weird behaviour

查看:115
本文介绍了PHP printf函数和它的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很困惑这些数字的含义。对我来说,似乎printf给了我错误的结果。

I'm baffled what these numbers mean. To me it seems that printf gives me wrong results.

echo printf("%.2f", 1);
// 1.004

echo printf("%.3f", 1);
// 1.005

echo printf("%.2f", 1.1234);
// 1.124

首先,它似乎打印了太多的小数,我没有知道这些数字是什么。有人可以解释一下这个问题吗?

First of all it seems to print too many decimals and I have no idea what those numbers are. Can someone shed some light on this matter?

推荐答案

简单。 printf() 有一个返回值,即:整数。该值是 - 结果字符串的长度。因此,你的代码做了两件事:

Simple. printf() has a return value, which is integer. And that value is - length of resulting string. Thus, your code is doing two things:


  • 首先,格式&输出你的字符串 printf()

  • 其次, echo()结果,这是每个字符串的长度。

  • First, format & output your string with printf()
  • Second, echo() the result, which is the length for each string.

这是因为你看到 1.004 例如,对于第一种情况。这是 1.00 4 (和的长度1.00 string是 4

That is because you see 1.004 for first case, for example. It's 1.00 with 4 (and length of "1.00" string is 4)

如果您打算打印格式化的字符串,请使用 printf ()原样:

If your intention is to print formatted string, either use printf() as it is:

printf("%.2f", 1);

或者使用 sprintf() with echo:

Or use sprintf() with echo:

echo sprintf("%.2f", 1);

这篇关于PHP printf函数和它的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆