以php双数据类型格式获取值 [英] Get value in php double data type format

查看:40
本文介绍了以php双数据类型格式获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$td = 4.0;
echo $td;

输出为4;但我想要双数据类型的实数(4.0);

The output is 4; But I want real number (4.0) in double data type;

推荐答案

首先,不要挑剔,但 PHP 没有您想要的类型*.当您执行 $td = 4.0; 时,您已经创建了一个 浮动.

First, not to be nitpicky, but PHP doesn't have the type you want*. When you do $td = 4.0; you have created a float.

如果你用 var_dump($td); 检查它,你会看到:float 4.由于这里没有真正的有效数字的概念,小数点后的零与存储值无关.

If you inspect it with var_dump($td);, you'll see: float 4. Since there isn't really a concept of significant figures here, the zero after the decimal is not relevant to the stored value.

第二,当你做echo $td;时,PHP会输出float 4的字符串表示.同样,如果没有以某种方式指定要显示 n 个小数位,PHP 将省略任何尾随零.再举一个例子,如果你这样做

Second, when you do echo $td;, PHP will output the string representation of float 4. Again, without somehow specifying that you want to display n decimal places, PHP will omit any trailing zeroes. For another example, if you did this

$td = 4.00010000;
echo $td;

你会看到

4.0001

这就是为什么其他答案/评论会引导您使用格式化解决方案.因为您真正需要做的不是更改变量的类型,因为它已经存储在适当的类型中.您只需要指定在将其转换为字符串时应如何显示.有不同的方法可以做到这一点.如果您使用printf,您可以指定一个数字要显示的小数位数.例如,您可以通过以下方式让它显示一个:

This is why the other answers/comments are guiding you toward a formatting solution. Because what you're really needing to do is not to change the type of the variable, because it's already stored in an appropriate type. You just need to specify how it should be displayed when it's converted to a string. There are different ways to do that. If you use printf, you can specify a number of decimal places to display. Here's how you make it show one, for example:

printf('%.1f', $td);

'%.1f' 是一个格式字符串..1 部分告诉它显示一位小数.但你并没有改变类型.这只是输出格式.

The '%.1f' is a format string. The .1 part is what tells it to show one decimal place. But you aren't changing the type. It's just output formatting.

*这是 PHP 的原生类型列表.我有点弄错了,它确实表明 float 是 double.

这篇关于以php双数据类型格式获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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