用PHP截断浮点数 [英] Truncate float numbers with PHP

查看:156
本文介绍了用PHP截断浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当一个浮点数需要在浮点数之后被截断到一个特定的数字时,结果是不容易完成的。例如,如果截断必须在点之后的第二位数字,数字应该是

45.8976 => 45.89,0.0185 => 0.01

(点后的第二个数字是)
函数如round(),number_format(),sprintf()四舍五入并打印出来
45.8976 => 45.90, 0.0185 => 0.02


我遇到了两个解决方案,我想知道它们是否足够好,哪一个更适合使用

  1.函数truncNumber($ number,$ prec = 2)
{
return bccomp($ number,0 ,10)== 0? $ number:round($ number - pow(0.1,bcadd($ prec,1))* 5,$ prec);

$ b $ 2.函数truncNumber($ number,$ prec = 2)
{
返回sprintf(%。。$ prec。f, ($ number * pow(10,$ prec))/ pow(10,$ prec));


解决方案



  floor(45.8976 * 100)/ 100; 

您不会找到更直接的函数,因为这是一种奇怪的事情。通常情况下,你会在数学上正确的。出于好奇 - 你需要什么?


When a float number needs to be truncated to a certain digit after the floating point, it turns out that it is not easy to be done. For example if the truncating has to be done to second digit after the point, the numbers should be
45.8976 => 45.89, 0.0185 => 0.01
( second digit after the point is not rounded according to the third digit after the point ).
Functions like round(), number_format(), sprintf() round the number and print out
45.8976 => 45.90, 0.0185 => 0.02

I have met two solutions and I am wondering if they are good enough and which one is better to be used

 1. function truncNumber( $number, $prec = 2 )
{
      return bccomp( $number, 0, 10 ) == 0 ? $number : round( $number - pow( 0.1, bcadd(   $prec, 1 ) ) * 5, $prec );
}

 2. function truncNumber($number, $prec = 2 )
{
  return sprintf( "%.".$prec."f", floor( $number*pow( 10, $prec ) )/pow( 10, $prec ) );
}

解决方案

floor will do as you ask.

floor(45.8976 * 100) / 100;

You won't find a more direct function for this, since it's a kind of odd thing to ask. Normally you'll round mathematically correct. Out of curiosity - What do you need this for?

这篇关于用PHP截断浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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