使用(int)和(double)一起截取小数时出现错误 [英] Error With Using (int) and (double) together to Cut off Decimals

查看:108
本文介绍了使用(int)和(double)一起截取小数时出现错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我有时将(int)与(double)一起使用时,它无法正常工作.
看一下PHP代码示例:

When I am using (int) with (double) some times it is not working correct.
Look At The PHP Code Example:

我需要保留2个小数并删除其他......

我知道number_format();功能,但我不能使用它.因为它是四舍五入的数字

I Need To LEAVE 2 Decimals And REMOVE Other...

I Know number_format(); function But I Cannot Use It. Because It Is Rounding Number

number_format(24.299,2);
输出:24.30
我需要:24.29

number_format(24.299,2);
Output: 24.30
I Need: 24.29

<?php

$str="158.2";

echo (double)$str; // Output: 158.2
echo (double)$str*100; // Output: 15820
echo (int)((double)$str*100); // Output: 15819 <-WHY? It Must To Be 15820, Why 15819? 
echo ((int)((double)$str*100)/100); // Output: 158.19
?>

我需要在数字中保留两位小数,并在不舍入的情况下将其舍去.

I need To leave two decimals in the number and cut other WITHOUT rounding.

推荐答案

由于浮点精度(例如,请参见以下问题:

Because of floating point precision (see for example this question: PHP - Floating Number Precision), 158.2 * 100 is not exactly 15820 but something like 15819.99999999.

现在(int)用于类型转换,不用于四舍五入,并且切掉该点之后的任何数字.

Now (int) is for type conversion, not for rounding, and any digits after the point are cut of.

我需要在数字中保留两位小数,并在不舍入的情况下将其舍去.

I need To leave two decimals in the number and cut other WITHOUT rounding.

这很容易:

number_format($str, 2);

更新

number_format 一轮,所以它有点复杂:

number_format does round, so it is a bit more complicated:

bcmul($str,100,0)/100

bcmul 以任意精度相乘,在这种情况下为0.结果:

bcmul multiplies with arbitrary precision, in this case 0. Results:

bcmul(158.2,100,0)/100 == 158.2
bcmul(24.299,100,0)/100 == 24.29

这篇关于使用(int)和(double)一起截取小数时出现错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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