php 在php中按小数点分割一个数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/412875/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Split a number by decimal point in php
提问by Par
How do I split a number by the decimal point in php?
如何在php中按小数点分割数字?
I've got $num = 15/4; which turns $num into 3.75. I would like to split out the 3 and the 75 parts, so $int = 3 and $dec = 75. My non-working code is:
我有 $num = 15/4; 这将 $num 变成 3.75。我想拆分 3 和 75 部分,所以 $int = 3 和 $dec = 75。我的非工作代码是:
$num = 15/4; // or $num = 3.75;
list($int, $dec) = split('.', $num);
but that results in empty $int and $dec.
但这会导致 $int 和 $dec 为空。
Thanks in advance.
提前致谢。
回答by xtofl
If you explodethe decimal representation of the number, you lose precision. If you don't mind, so be it (that's ok for textual representation). Take the locale into account! We Belgians use a comma (at least the non-programming ones :).
如果您explode使用数字的十进制表示,则会失去精度。如果你不介意,就这样吧(文本表示没问题)。考虑地域!我们比利时人使用逗号(至少是非编程的:)。
If you domind (for computations e.g.), you can use the floorfunction:
如果你做的头脑(用于计算如),你可以使用floor函数:
$num = 15/4
$intpart = floor( $num ) // results in 3
$fraction = $num - $intpart // results in 0.75
Note: this is for positive numbers. For negative numbers you can invert the sign, use the positive approach, and reinvert the sign of the int part.
注意:这是针对正数的。对于负数,您可以反转符号,使用正方法,并重新反转 int 部分的符号。
回答by Paul Dixon
回答by ólafur Waage
$num = 15/4; // or $num = 3.75;
list($int, $dec) = explode('.', $num);
回答by Tom Haigh
$int = $num > 0 ? floor($num) : ceil($num);
$dec = $num - $int;
If you want $decto be positive when $numis negative (like the other answers) you could do:
如果您想$dec在消极时积极$num(如其他答案),您可以这样做:
$dec = abs($num - $int);
回答by Aaron Smith
$num = 3.75;
$fraction = $num - (int) $num;
回答by Andrew Griggs
$num = 15/4;
substr(strrchr($num, "."), 1)
回答by thedude
This works for positive AND negative numbers:
这适用于正数和负数:
$num = 5.7;
$whole = (int) $num; // 5
$frac = $num - (int) $num; // .7
回答by Milos
In case when you don't want to lose precision, you can use these:
如果您不想失去精度,可以使用这些:
$number = 10.10;
$number = number_format($number, 2, ".", ",");
sscanf($number, '%d.%d', $whole, $fraction);
// you will get $whole = 10, $fraction = 10

