Set precision for a float number in PHP - php

I get a number from database and this number might be either float or int.
I need to set the decimal precision of the number to 3, which makes the number not longer than (regarding decimals) 5.020 or 1518845.756.
Using PHP
round($number, $precision)
I see a problem:
It rounds the number. I need a function to only cut the decimals short, without changing their values which round( ) seems not to follow.

You can use number_format() to achieve this:
echo number_format((float) $number, $precision, '.', '');
This would convert 1518845.756789 to 1518845.757.
But if you just want to cut off the number of decimal places short to 3, and not round, then you can do the following:
$number = intval($number * ($p = pow(10, $precision))) / $p;
It may look intimidating at first, but the concept is really simple. You have a number, you multiply it by 103 (it becomes 1518845756.789), cast it to an integer so everything after the 3 decimal places is removed (becomes 1518845756), and then divide the result by 103 (becomes 1518845.756).
Demo

Its sound like floor with decimals. So you can try something like
floor($number*1000)/1000

If I understand correctly, you would not want rounding to occur and you would want the precision to be 3.
So the idea is to use number_format() for a precision of 4 and then remove the last digit:
$number = '1518845.756789';
$precision = 3;
echo substr(number_format($number, $precision+1, '.', ''), 0, -1);
Will display:
1518845.756
rather than:
1518845.757
Links : number_format() , substr()

See this answer for more details.
function numberPrecision($number, $decimals = 0)
{
$negation = ($number < 0) ? (-1) : 1;
$coefficient = pow(10, $decimals);
return $negation * floor((string)(abs($number) * $coefficient)) / $coefficient;
}

$num=5.1239;
$testnum=intval($num*1000)/1000;
echo $testnum; //return 5.123

Related

How to transform last two numbers to decimal (int to float) in php?

I need transform 100 to 1.00, 345 to 3.45 or any number with 3 digits or more to record in db like a decimal.
Don't need add .00, just transform last two numbers in decimal.
I try number_format($num, 2) but is wrong.
It seems, that you want to divide your numbers to 100, so using number_format() with the appropriate $decimal_separator and $thousands_separator is an option:
<?php
echo number_format($num / 100, 2, '.', '');
?>
Since you are converting from an integer to a float, you can achieve this simply by dividing the number by 100.
$input = 100;
$value = floatval($input) / 100;
$value = number_format($value, 2);
echo $value;
You may then use number_format (as you were using before) to force two decimal places after any evenly divided float numbers (such as 100).
Demo: PHP Sandbox Example

Unexpected result for number_format and sprintf when trying to display number with two decimals

I have a calculation that returns this double: 6.4971508379888. If I cast it to a float and echo it, it's the same number. I want to display (not round) the number with only two decimals, so I tried:
number_format((float)$number, 2, '.', '')
and
sprintf('%0.2f', (float)$number)
but in both cases I see 6.50 instead of 6.49. Why is this happening?
PHP automatically round the value based on given precision
If you want your expected results then follow the following code.
$precision = 2;
$number = floor($number * pow(10,$precision))/pow(10,$precision);
echo number_format((float)$number, $precision, '.', '');
This is a slight modification to the accepted answer because the solution provided wasn't giving an accurate result. It was causing the last digit to get rounded (down).
$digits = 2;
$number = floor($number * pow(10, ($digits + 1)) / pow(10, ($digits + 1));
echo number_format($number, $digits, '.', '');
Also, there should be no need to type-cast to a float when passing the number to number_format(). The calculation (and the function itself) will automatically set the type accordingly.

Delete digits after two decimal point not round number using PHP

My number: 53.199999999999996
I have tried all of these:
sprintf("%01.2f", $number); // 53.20
sprintf('%0.2f', $number); // 53.20
floor(($number * 100)) / 100; // 53.2
intval(($number * 100)) / 100; // 53.2
I want: 53.19
How can I do that?
You can use number_format(): http://php.net/number_format
$number = 53.1999999
echo int() number_format((float)$number, 2, '.', '');
//53.19
You need floor() in this way:
echo floor($number*100)/100;
Or you cast to integer:
echo 0.01 * (int)($number*100);
This way it will not be rounding up.
I have checked and using intval its works on php version 5.3, however you have mentioned its not worked at your end.
$number = 53.1999999;
echo intval(($number*100))/100;
you must set precision (floating point) before set this float number
ini_set('precision', 17);
$number = 53.199999999999996;
$number = ($pos = strpos($number,'.')) ? substr($number,0,$pos + 3) : number_format($number);
echo $number ;
output :
53.19
Link
PHP round float numbers with this setting, if you set variable without quoting that like :
$number = 53.199999999999996;
echo $number;
PHP will round this number
after var_dump , print ,echo , ... output will be :
53.2
our you can set number value with quoting
$number = '53.199999999999996';
echo $number;
PHP do not round this because it's string now!

How to get first 4 digits from an integer in PHP

After a few calculations I get:
$int = 14.285714285714;
How can I take only the first four digits? Expected output: 14.28
Doing this with string functions is absolutely the wrong way to go about this, and these nearly identical answers look pretty spammy. If you want to round a number, round a number!
$int = round(14.285714285714, 2);
To truncate (as opposed to rounding), floor is the correct function in PHP:
$int = floor(14.285714285714 * 100) / 100;
Both work without any type conversions or casting.
Also note that a number with decimal places is categorically not an integer.
use substr function
$int = 14.285714285714;
echo substr($int, 0, 5);
$newint = (float)substr($int, 0, 5);
IF you want to round the number you can use
round($int, 2);
OUTPUT WILL BE : 14.29
LINK HOW TO ROUND
Try number format,
string number_format ( float $number [, int $decimals = 0 ] )
so
$int = 14.285714285714;
$small = (float)number_format ( $int ,2,'.', '' ); //gets rid of the "," for thousand separator
http://us2.php.net/manual/en/function.number-format.php
floor(100 * 14.285714285714) / 100
14.28

PHP How do I round down to two decimal places? [duplicate]

This question already has answers here:
Truncate float numbers with PHP
(14 answers)
Closed 11 months ago.
I need to round down a decimal in PHP to two decimal places so that:
49.955
becomes...
49.95
I have tried number_format, but this just rounds the value to 49.96. I cannot use substr because the number may be smaller (such as 7.950). I've been unable to find an answer to this so far.
Any help much appreciated.
This can work: floor($number * 100) / 100
Unfortunately, none of the previous answers (including the accepted one) works for all possible inputs.
1) sprintf('%1.'.$precision.'f', $val)
Fails with a precision of 2 : 14.239 should return 14.23 (but in this case returns 14.24).
2) floatval(substr($val, 0, strpos($val, '.') + $precision + 1))
Fails with a precision of 0 : 14 should return 14 (but in this case returns 1)
3) substr($val, 0, strrpos($val, '.', 0) + (1 + $precision))
Fails with a precision of 0 : -1 should return -1 (but in this case returns '-')
4) floor($val * pow(10, $precision)) / pow(10, $precision)
Although I used this one extensively, I recently discovered a flaw in it ; it fails for some values too. With a precision of 2 : 2.05 should return 2.05 (but in this case returns 2.04 !!)
So far the only way to pass all my tests is unfortunately to use string manipulation. My solution based on rationalboss one, is :
function floorDec($val, $precision = 2) {
if ($precision < 0) { $precision = 0; }
$numPointPosition = intval(strpos($val, '.'));
if ($numPointPosition === 0) { //$val is an integer
return $val;
}
return floatval(substr($val, 0, $numPointPosition + $precision + 1));
}
This function works with positive and negative numbers, as well as any precision needed.
Here is a nice function that does the trick without using string functions:
<?php
function floorp($val, $precision)
{
$mult = pow(10, $precision); // Can be cached in lookup table
return floor($val * $mult) / $mult;
}
print floorp(49.955, 2);
?>
An other option is to subtract a fraction before rounding:
function floorp($val, $precision)
{
$half = 0.5 / pow(10, $precision); // Can be cached in a lookup table
return round($val - $half, $precision);
}
I think there is quite a simple way to achieve this:
$rounded = bcdiv($val, 1, $precision);
Here is a working example. You need BCMath installed but I think it's normally bundled with a PHP installation. :) Here is the documentation.
function roundDown($decimal, $precision)
{
$sign = $decimal > 0 ? 1 : -1;
$base = pow(10, $precision);
return floor(abs($decimal) * $base) / $base * $sign;
}
// Examples
roundDown(49.955, 2); // output: 49.95
roundDown(-3.14159, 4); // output: -3.1415
roundDown(1000.000000019, 8); // output: 1000.00000001
This function works with positive and negative decimals at any precision.
Code example here: http://codepad.org/1jzXjE5L
Multiply your input by 100, floor() it, then divide the result by 100.
You can use bcdiv PHP function.
bcdiv(49.955, 1, 2)
Try the round() function
Like this: round($num, 2, PHP_ROUND_HALF_DOWN);
For anyone in need, I've used a little trick to overcome math functions malfunctioning, like for example floor or intval(9.7*100)=969 weird.
function floor_at_decimals($amount, $precision = 2)
{
$precise = pow(10, $precision);
return floor(($amount * $precise) + 0.1) / $precise;
}
So adding little amount (that will be floored anyways) fixes the issue somehow.
Use formatted output
sprintf("%1.2f",49.955) //49.95
DEMO
You can use:
$num = 49.9555;
echo substr($num, 0, strpos($num, '.') + 3);
function floorToPrecision($val, $precision = 2) {
return floor(round($val * pow(10, $precision), $precision)) / pow(10, $precision);
}
An alternative solution using regex which should work for all positive or negative numbers, whole or with decimals:
if (preg_match('/^-?(\d+\.?\d{1,2})\d*$/', $originalValue, $matches)){
$roundedValue = $matches[1];
} else {
throw new \Exception('Cannot round down properly '.$originalValue.' to two decimal places');
}
Based on #huysentruitw and #Alex answer, I came up with following function that should do the trick.
It pass all tests given in Alex's answer (as why this is not possible) and build upon huysentruitw's answer.
function trim_number($number, $decimalPlaces) {
$delta = (0 <=> $number) * (0.5 / pow(10, $decimalPlaces));
$result = round($number + $delta, $decimalPlaces);
return $result ?: 0; // get rid of negative zero
}
The key is to add or subtract delta based on original number sign, to support trimming also negative numbers.
Last thing is to get rid of negative zeros (-0) as that can be unwanted behaviour.
Link to "test" playground.
EDIT: bcdiv seems to be the way to go.
// round afterwards to cast 0.00 to 0
// set $divider to 1 when no division is required
round(bcdiv($number, $divider, $decimalPlaces), $decimalPlaces);
sprintf("%1.2f",49.955) //49.95
if you need to truncate decimals without rounding - this is not suitable, because it will work correctly until 49.955 at the end, if number is more eg 49.957 it will round to 49.96
It seems for me that Lght`s answer with floor is most universal.
Did you try round($val,2) ?
More information about the round() function

Categories