Split a number by decimal point in php

2020-03-03 07:04发布

How do I split a number by the decimal point in 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; // or $num = 3.75;
list($int, $dec) = split('.', $num);

but that results in empty $int and $dec.

Thanks in advance.

标签: php split
8条回答
混吃等死
2楼-- · 2020-03-03 07:18
$num = 15/4; // or $num = 3.75;
list($int, $dec) = explode('.', $num);
查看更多
做个烂人
3楼-- · 2020-03-03 07:22
$num = 3.75;
$fraction = $num - (int) $num;
查看更多
不美不萌又怎样
4楼-- · 2020-03-03 07:24
$int = $num > 0 ? floor($num) : ceil($num);
$dec = $num - $int;

If you want $dec to be positive when $num is negative (like the other answers) you could do:

$dec = abs($num - $int);
查看更多
我命由我不由天
5楼-- · 2020-03-03 07:27

This works for positive AND negative numbers:

$num = 5.7;
$whole = (int) $num;         //  5
$frac  = $num - (int) $num;  // .7
查看更多
萌系小妹纸
6楼-- · 2020-03-03 07:31

If you explode the 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 :).

If you do mind (for computations e.g.), you can use the floor function:

$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.

查看更多
我只想做你的唯一
7楼-- · 2020-03-03 07:31
$num = 15/4;
substr(strrchr($num, "."), 1)
查看更多
登录 后发表回答