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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:40:28  来源:igfitidea点击:

Split a number by decimal point in php

phpsplit

提问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

Try explode

尝试爆炸

list($int,$dec)=explode('.', $num);

as you don't really need to use a regex based split. Splitwasn't working for you as a '.' character would need escaping to provide a literal match.

因为您实际上并不需要使用基于正则表达式的拆分。Split不适合您作为“。” 字符需要转义以提供文字匹配。

回答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