解释php输出 [英] explain php output

查看:189
本文介绍了解释php输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以在PHP中解释以下输出?

Can anyone explain the below output in PHP?

$num1 = (1.65 - 1.00);
echo "<br><br>num1 = " . $num1;   // Output: int = 0.65

$num_int1 = $num1 * 100;
echo "<br><br>int = " . $num_int1;   // Output: int = 65

$num_int2 = (int) $num_int1;
echo "<br><br>int = " . $num_int2;   // Output: int = 64

为什么$ num_int2是64?

Why $num_int2 is 64?

感谢您的帮助。

推荐答案

我为Authorize.Net写的文章(在您的特定情况下 $ num_int1 是一个浮点数,即使它看起来像一个整数):

From an article I wrote for Authorize.Net (in your specific case $num_int1 is a float even if it looks like an integer):

一加一等于二,对吧? .2加上1.4乘以10?等于16,对不对?如果你正在用PHP(或大多数其他编程语言)进行数学运算:

One plus one equals two, right? How about .2 plus 1.4 times 10? That equals 16, right? Not if you're doing the math with PHP (or most other programming languages):

echo floor((0.2 + 1.4) * 10); // Should be 16. But it's 15!

这是因为浮点数在内部如何处理。它们用固定数目的小数位数表示,并且可能导致数字不像您期望的那样相加。在内部我们的.2加上1.4乘以10的例子计算到大约15.9999999998左右。这种数学是好的,当使用数字,不必像百分比那样精确。但是,在处理货币精确问题时,一分钱或一美元在这里或在那里加起来很快,没有人喜欢在短缺的任何缺失的钱。

This is due to how floating point numbers are handled internally. They are represented with a fixed number of decimal places and can result in numbers that do not add up quite like you expect. Internally our .2 plus 1.4 times 10 example computes to roughly 15.9999999998 or so. This kind of math is fine when working with numbers that do not have to be precise like percentages. But when working with money precision matters as a penny or a dollar missing here or there adds up quickly and no one likes being on the short end of any missing money.

The BC Math Solution

The BC Math Solution

幸运的是,PHP提供了 BC数学扩展是任意精度数学的PHP提供二进制计算器支持任何大小和精度的数字,表示为字符串。换句话说,你可以使用这个扩展做货币价值的精确数学。 BC Math扩展包含函数,允许您以最精确的方式执行最常见的操作,包括< a href =http://us2.php.net/manual/en/function.bcadd.php>添加,减法乘法细节

Fortunately PHP offers the BC Math extension which is "for arbitrary precision mathematics PHP offers the Binary Calculator which supports numbers of any size and precision, represented as strings." In other words, you can do precise math with monetary values using this extension. The BC Math extension contains functions that allow you to perform the most common operations with precision including addition, subtraction, multiplication, and division.

更好的示例

这里是和上面相同的例子,但是使用bcadd()函数为我们做数学。它需要三个参数。前两个是我们希望添加的值,第三个是我们希望精确到的小数位数。由于我们使用的是金钱,我们将精度设置为两个小数。

Here's the same example as above but using the bcadd() function to do the math for us. It takes three parameters. The first two are the values we wish to add and the third is the number of decimal places we wish to be precise to. Since we're working with money we'll set the precision to be two decimal palces.

echo floor(bcadd('0.2', '1.4', 2) * 10); // It's 16 like we would expect it to be.

这篇关于解释php输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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