Reputation: 25
I have a number 1.5
, 1.6666
or 1.777
.
How can I extract those float values from the int part? Not just round but separate them in different vars.
Expected output is $var1 = 1
and $var2 = 0.5
for 1.5
.
Upvotes: 0
Views: 94
Reputation: 43572
You can do this with multiple ways. Lets say $v = 1.56;
:
Example #1
$m = explode('.', $v);
$v1 = $m[0];
$v2 = '0.' . $m[1];
print_r("#1: \$v1 = $v1; \$v2 = $v2;\n");
Example #2
preg_match('~^(\d+)\.(\d+)$~', $v, $m);
$v1 = $m[1];
$v2 = '0.' . $m[2];
print_r("#2: \$v1 = $v1; \$v2 = $v2;\n");
Example #3
$v1 = substr($v, 0, strpos($v, '.'));
$v2 = '0.' . substr($v, strpos($v, '.') + 1);
print_r("#3: \$v1 = $v1; \$v2 = $v2;\n");
Example #4
$v1 = floor($v1);
$v2 = $v - $v1;
print_r("#4: \$v1 = $v1; \$v2 = $v2;\n");
All examples will output >
#1: $v1 = 1; $v2 = 0.56;
#2: $v1 = 1; $v2 = 0.56;
#3: $v1 = 1; $v2 = 0.56;
#4: $v1 = 1; $v2 = 0.56;
Watch out for the big float numbers. See BC Math functions for those.
Upvotes: 0
Reputation: 21440
You could also use:
$var = 1.5;
$arr = explode('.', $var);
$wholeNum = $arr[0]; // 1
$decimalNum = $arr[1]; // 5
Upvotes: 0
Reputation: 10473
First get the integer portion and then subtract it from the original.
$original = 1.6666;
$intPortion = intval($original);
$floatPortion = $original - $intPortion;
Upvotes: 1
Reputation: 71384
This is probably your best bet:
$float = 1.666;
$remainder = fmod($float, 1);
$integer = intval($float, 10);
Upvotes: 0