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:35

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
查看更多
倾城 Initia
3楼-- · 2020-03-03 07:38

Try explode

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

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

查看更多
登录 后发表回答