Par
Par

Reputation: 125

Split a number by decimal point in php

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.

Upvotes: 8

Views: 27862

Answers (8)

xtofl
xtofl

Reputation: 41509

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
if ($num > 0) {
    $intpart = floor( $num );    // results in 3
    $fraction = $num - $intpart; // results in 0.75
} else {
    $intpart = ceil( $num );     // results in -3
    $fraction = $num - $intpart; // results in -0.75
}

Upvotes: 24

Tom Haigh
Tom Haigh

Reputation: 57815

$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);

Upvotes: 4

thedude
thedude

Reputation: 627

This works for positive AND negative numbers:

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

Upvotes: 2

Milos
Milos

Reputation: 677

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

Upvotes: 2

Aaron Smith
Aaron Smith

Reputation: 71

$num = 3.75;
$fraction = $num - (int) $num;

Upvotes: 2

Andrew Griggs
Andrew Griggs

Reputation: 11

$num = 15/4;
substr(strrchr($num, "."), 1)

Upvotes: 1

Paul Dixon
Paul Dixon

Reputation: 300845

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.

Upvotes: 7

Ólafur Waage
Ólafur Waage

Reputation: 69991

$num = 15/4; // or $num = 3.75;
list($int, $dec) = explode('.', $num);

Upvotes: 7

Related Questions