如何获取一个数的整数部分和小数部分?

发布于 2024-11-18 22:08:19 字数 79 浏览 2 评论 0原文

比如说,给定 1.25 - 我如何获得这个数字的“1”和“25”部分?

我需要检查小数部分是 .0、.25、.5 还是 .75。

Given, say, 1.25 - how do I get "1" and ."25" parts of this number?

I need to check if the decimal part is .0, .25, .5, or .75.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(20

檐上三寸雪 2024-11-25 22:08:19
$n = 1.25;
$whole = floor($n);      // 1
$fraction = $n - $whole; // .25

然后与 1/4、1/2、3/4 等进行比较。


如果是负数,请使用以下命令:

function NumberBreakdown($number, $returnUnsigned = false)
{
  $negative = 1;
  if ($number < 0)
  {
    $negative = -1;
    $number *= -1;
  }

  if ($returnUnsigned){
    return array(
      floor($number),
      ($number - floor($number))
    );
  }

  return array(
    floor($number) * $negative,
    ($number - floor($number)) * $negative
  );
}

$returnUnsigned 会阻止其生成 -1.25-1 & -0.25

$n = 1.25;
$whole = floor($n);      // 1
$fraction = $n - $whole; // .25

Then compare against 1/4, 1/2, 3/4, etc.


In cases of negative numbers, use this:

function NumberBreakdown($number, $returnUnsigned = false)
{
  $negative = 1;
  if ($number < 0)
  {
    $negative = -1;
    $number *= -1;
  }

  if ($returnUnsigned){
    return array(
      floor($number),
      ($number - floor($number))
    );
  }

  return array(
    floor($number) * $negative,
    ($number - floor($number)) * $negative
  );
}

The $returnUnsigned stops it from making -1.25 in to -1 & -0.25

冬天旳寂寞 2024-11-25 22:08:19

此代码将为您拆分它:

list($whole, $decimal) = explode('.', $your_number);

其中 $whole 是整数,$decimal 将包含小数点后的数字。

This code will split it up for you:

list($whole, $decimal) = explode('.', $your_number);

where $whole is the whole number and $decimal will have the digits after the decimal point.

笨笨の傻瓜 2024-11-25 22:08:19

Floor() 方法不适用于负数。这每次都有效:

$num = 5.7;
$whole = (int) $num;  // 5
$frac  = $num - $whole;  // .7

...也适用于底片(相同的代码,不同的数字):

$num = -5.7;
$whole = (int) $num;  // -5
$frac  = $num - $whole;  // -.7

The floor() method doesn't work for negative numbers. This works every time:

$num = 5.7;
$whole = (int) $num;  // 5
$frac  = $num - $whole;  // .7

...also works for negatives (same code, different number):

$num = -5.7;
$whole = (int) $num;  // -5
$frac  = $num - $whole;  // -.7
违心° 2024-11-25 22:08:19

只是为了与众不同:)

list($whole, $decimal) = sscanf(1.5, '%d.%d');

CodePad

作为一个额外的好处,它只会在双方都包含数字的情况下进行拆分。

Just to be different :)

list($whole, $decimal) = sscanf(1.5, '%d.%d');

CodePad.

As an added benefit, it will only split where both sides consist of digits.

音栖息无 2024-11-25 22:08:19

一个简短的方法(使用下限和 fmod)

$var = "1.25";
$whole = floor($var);     // 1
$decimal = fmod($var, 1); //0.25

然后将 $decimal 与 0、.25、.5 或 .75 进行比较

a short way (use floor and fmod)

$var = "1.25";
$whole = floor($var);     // 1
$decimal = fmod($var, 1); //0.25

then compare $decimal to 0, .25, .5, or .75

临风闻羌笛 2024-11-25 22:08:19

将其转换为 int 并减去

$integer = (int)$your_number;
$decimal = $your_number - $integer;

或者只是为了得到小数以进行比较

$decimal = $your_number - (int)$your_number

Cast it as an int and subtract

$integer = (int)$your_number;
$decimal = $your_number - $integer;

Or just to get the decimal for comparison

$decimal = $your_number - (int)$your_number
∝单色的世界 2024-11-25 22:08:19

对于那些想要将整数部分和小数部分拆分为两个整数分隔值的人来说,这只是一个新的简单解决方案:

5.25 ->整数部分:5;小数部分:25

$num = 5.25;
$int_part = intval($num);
$dec_part = $num * 100 % 100;

这种方式不涉及基于字符串的函数,并且可以防止其他数学运算中可能出现的准确性问题(例如使用 0.49999999999999 而不是 0.5)。

还没有对极值进行彻底测试,但它对我来说对于价格计算来说效果很好。

但是,要小心!现在从-5.25你得到:整数部分:-5;小数部分:-25

如果您想始终获得正数,只需在计算前添加 abs()

$num = -5.25;
$num = abs($num);
$int_part = intval($num);
$dec_part = $num * 100 % 100;

最后,打印带有 2 位小数的价格的奖励片段:

$message = sprintf("Your price: %d.%02d Eur", $int_part, $dec_part);

。 ..这样你就可以避免得到 5.5 而不是 5.05。 ;)

Just a new simple solution, for those of you who want to get the Integer part and Decimal part splitted as two integer separated values:

5.25 -> Int part: 5; Decimal part: 25

$num = 5.25;
$int_part = intval($num);
$dec_part = $num * 100 % 100;

This way is not involving string based functions, and is preventing accuracy problems which may arise in other math operations (such as having 0.49999999999999 instead of 0.5).

Haven't tested thoroughly with extreme values, but it works fine for me for price calculations.

But, watch out! Now from -5.25 you get: Integer part: -5; Decimal part: -25

In case you want to get always positive numbers, simply add abs() before the calculations:

$num = -5.25;
$num = abs($num);
$int_part = intval($num);
$dec_part = $num * 100 % 100;

Finally, bonus snippet for printing prices with 2 decimals:

$message = sprintf("Your price: %d.%02d Eur", $int_part, $dec_part);

...so that you avoid getting 5.5 instead of 5.05. ;)

轻许诺言 2024-11-25 22:08:19

还有一个 fmod 函数,可以使用:
fmod($my_var, 1)
将返回相同的结果,但有时会出现较小的舍入误差。

There's a fmod function too, that can be used :
fmod($my_var, 1)
will return the same result, but sometime with a small round error.

云雾 2024-11-25 22:08:19

PHP 5.4+

$n = 12.343;
intval($n); // 12
explode('.', number_format($n, 1))[1]; // 3
explode('.', number_format($n, 2))[1]; // 34
explode('.', number_format($n, 3))[1]; // 343
explode('.', number_format($n, 4))[1]; // 3430

PHP 5.4+

$n = 12.343;
intval($n); // 12
explode('.', number_format($n, 1))[1]; // 3
explode('.', number_format($n, 2))[1]; // 34
explode('.', number_format($n, 3))[1]; // 343
explode('.', number_format($n, 4))[1]; // 3430
半城柳色半声笛 2024-11-25 22:08:19

这是我使用的方式:

$float = 4.3;    

$dec = ltrim(($float - floor($float)),"0."); // result .3

This is the way which I use:

$float = 4.3;    

$dec = ltrim(($float - floor($float)),"0."); // result .3
淡淡の花香 2024-11-25 22:08:19

Brad Christie 的方法本质上是正确的,但可以写得更简洁。

function extractFraction ($value) 
{
    $fraction   = $value - floor ($value);
    if ($value < 0)
    {
        $fraction *= -1;
    }

    return $fraction;
}

这与他的方法相同,但更短,因此更容易理解。

Brad Christie's method is essentially correct but it can be written more concisely.

function extractFraction ($value) 
{
    $fraction   = $value - floor ($value);
    if ($value < 0)
    {
        $fraction *= -1;
    }

    return $fraction;
}

This is equivalent to his method but shorter and hopefully easier to understand as a result.

烟雨凡馨 2024-11-25 22:08:19

我很难找到一种方法来实际区分美元金额和小数点后的金额。我想我大部分都弄清楚了,并且想分享是否有人遇到麻烦

所以基本上...

如果价格是1234.44...整体将是1234,小数将是44,或者

如果价格是1234.01...整体将是1234,小数点为 01,或者

如果价格为 1234.10...整体为 1234,小数点为 10

,依此类推

$price = 1234.44;

$whole = intval($price); // 1234
$decimal1 = $price - $whole; // 0.44000000000005 uh oh! that's why it needs... (see next line)
$decimal2 = round($decimal1, 2); // 0.44 this will round off the excess numbers
$decimal = substr($decimal2, 2); // 44 this removed the first 2 characters

if ($decimal == 1) { $decimal = 10; } // Michel's warning is correct...
if ($decimal == 2) { $decimal = 20; } // if the price is 1234.10... the decimal will be 1...
if ($decimal == 3) { $decimal = 30; } // so make sure to add these rules too
if ($decimal == 4) { $decimal = 40; }
if ($decimal == 5) { $decimal = 50; }
if ($decimal == 6) { $decimal = 60; }
if ($decimal == 7) { $decimal = 70; }
if ($decimal == 8) { $decimal = 80; }
if ($decimal == 9) { $decimal = 90; }

echo 'The dollar amount is ' . $whole . ' and the decimal amount is ' . $decimal;

I was having a hard time finding a way to actually separate the dollar amount and the amount after the decimal. I think I figured it out mostly and thought to share if any of yall were having trouble

So basically...

if price is 1234.44... whole would be 1234 and decimal would be 44 or

if price is 1234.01... whole would be 1234 and decimal would be 01 or

if price is 1234.10... whole would be 1234 and decimal would be 10

and so forth

$price = 1234.44;

$whole = intval($price); // 1234
$decimal1 = $price - $whole; // 0.44000000000005 uh oh! that's why it needs... (see next line)
$decimal2 = round($decimal1, 2); // 0.44 this will round off the excess numbers
$decimal = substr($decimal2, 2); // 44 this removed the first 2 characters

if ($decimal == 1) { $decimal = 10; } // Michel's warning is correct...
if ($decimal == 2) { $decimal = 20; } // if the price is 1234.10... the decimal will be 1...
if ($decimal == 3) { $decimal = 30; } // so make sure to add these rules too
if ($decimal == 4) { $decimal = 40; }
if ($decimal == 5) { $decimal = 50; }
if ($decimal == 6) { $decimal = 60; }
if ($decimal == 7) { $decimal = 70; }
if ($decimal == 8) { $decimal = 80; }
if ($decimal == 9) { $decimal = 90; }

echo 'The dollar amount is ' . $whole . ' and the decimal amount is ' . $decimal;
○闲身 2024-11-25 22:08:19
$x = 1.24

$result = $x - floor($x);

echo $result; // .24
$x = 1.24

$result = $x - floor($x);

echo $result; // .24
能怎样 2024-11-25 22:08:19

如果你可以指望它总是有 2 个小数位,你可以只使用字符串操作:

$decimal = 1.25;
substr($decimal,-2);  // returns "25" as a string

不知道性能,但对于我的简单情况来说,这要好得多......

If you can count on it always having 2 decimal places, you can just use a string operation:

$decimal = 1.25;
substr($decimal,-2);  // returns "25" as a string

No idea of performance but for my simple case this was much better...

把人绕傻吧 2024-11-25 22:08:19

为了防止额外的浮点小数(即 50.85 - 50 给出 0.850000000852),在我的例子中,我只需要 2 位小数来表示钱分。

$n = 50.85;
$whole = intval($n);
$fraction = $n * 100 % 100;

To prevent the extra float decimal (i.e. 50.85 - 50 give 0.850000000852), in my case I just need 2 decimals for money cents.

$n = 50.85;
$whole = intval($n);
$fraction = $n * 100 % 100;
居里长安 2024-11-25 22:08:19

试试这个方法...这样更容易

$var = "0.98";

$decimal = strrchr($var,".");

$whole_no = $var-$decimal;

echo $whole_no;

echo str_replace(".", "", $decimal);

Try it this way... it's easier like this

$var = "0.98";

$decimal = strrchr($var,".");

$whole_no = $var-$decimal;

echo $whole_no;

echo str_replace(".", "", $decimal);
忆离笙 2024-11-25 22:08:19

你也可以使用这样的东西:

preg_match("/([0-9]+)\.([0-9]+)/", $number, $matches);

You could also use something like this:

preg_match("/([0-9]+)\.([0-9]+)/", $number, $matches);
空城缀染半城烟沙 2024-11-25 22:08:19

如果您希望对两半进行显式类型转换,那么 sscanf() 是一个很好的调用。

代码:(Demo)

var_dump(sscanf(1.25, '%d%f'));

输出:

array(2) {
  [0]=>
  int(1)
  [1]=>
  float(0.25)
}

或者您可以单独分配两个变量:

sscanf(1.25, '%d%f', $int, $float);
var_dump($int);
var_dump($float);

将小数部分转换为浮点数是例如,当将小时的十进制表达式转换为小时和分钟时特别有用。 (演示

$decimalTimes = [
    6,
    7.2,
    8.78,
];

foreach ($decimalTimes as $decimalTime) {
    sscanf($decimalTime, '%d%f', $hours, $minutes);
    printf('%dh%02dm', $hours, round($minutes * 60));
    echo "\n";
}

输出:

6h00m
7h12m
8h47m  // if round() was not used, this would be 8h46m

If you want the two halves to be explicitly type cast, then sscanf() is a great call.

Code: (Demo)

var_dump(sscanf(1.25, '%d%f'));

Output:

array(2) {
  [0]=>
  int(1)
  [1]=>
  float(0.25)
}

Or you can assign the two variables individually:

sscanf(1.25, '%d%f', $int, $float);
var_dump($int);
var_dump($float);

Casting the decimal portion as a float is particularly useful when, say, converting decimal expression of hours to hours and minutes. (Demo)

$decimalTimes = [
    6,
    7.2,
    8.78,
];

foreach ($decimalTimes as $decimalTime) {
    sscanf($decimalTime, '%d%f', $hours, $minutes);
    printf('%dh%02dm', $hours, round($minutes * 60));
    echo "\n";
}

Output:

6h00m
7h12m
8h47m  // if round() was not used, this would be 8h46m
美煞众生 2024-11-25 22:08:19

这里没有看到简单的模数...

$number         = 1.25;
$wholeAsFloat   = floor($number);   // 1.00
$wholeAsInt     = intval($number);  // 1
$decimal        = $number % 1;      // 0.25

在这种情况下,获取 $wholeAs?$decimal 并不依赖于另一个。 (您可以独立获取 3 个输出中的 1 个。)我显示了 $wholeAsFloat$wholeAsInt 因为 floor() 返回一个 float 类型数字,即使它返回的数字始终是整数。 (如果您将结果传递给类型提示的函数参数,这一点很重要。)

我希望将浮点数的小时/分钟(例如 96.25)分别拆分为小时和分钟,以用于 DateInterval 实例为 96 小时 15 分钟。我这样做如下:

$interval = new \DateInterval(sprintf("PT%dH%dM", intval($hours), (($hours % 1) * 60)));

在我的情况下,我不关心秒数。

Not seen a simple modulus here...

$number         = 1.25;
$wholeAsFloat   = floor($number);   // 1.00
$wholeAsInt     = intval($number);  // 1
$decimal        = $number % 1;      // 0.25

In this case getting both $wholeAs? and $decimal don't depend on the other. (You can just take 1 of the 3 outputs independently.) I've shown $wholeAsFloat and $wholeAsInt because floor() returns a float type number even though the number it returns will always be whole. (This is important if you're passing the result into a type-hinted function parameter.)

I wanted this to split a floating point number of hours/minutes, e.g. 96.25, into hours and minutes separately for a DateInterval instance as 96 hours 15 minutes. I did this as follows:

$interval = new \DateInterval(sprintf("PT%dH%dM", intval($hours), (($hours % 1) * 60)));

I didn't care about seconds in my case.

你げ笑在眉眼 2024-11-25 22:08:19
val = -3.1234

fraction = abs(val - as.integer(val) ) 
val = -3.1234

fraction = abs(val - as.integer(val) ) 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文