PHP round up or round down depending on decimal value [duplicate] - php

This question already has answers here:
Show a number to two decimal places
(25 answers)
Closed 6 years ago.
I have a php variable that I would like to round up if it closest value is i.e
113.845602277119 so this var would become 113.85
and round down if var is i.e 270.27388400703 would become 270.27 NOT 270.28
I presume i'll need a function to check the decimal value and update accordingly?
or a better example of what I want.
i.e this dynamic number 16.94502 I want this to round down to 16.94 the .9452 is closest to .95 but as the var is dynamic I need a check to do the inverse, other times the var could be 41.1378 is closest to .14 and so I want a round up

Use PHP round() function:
Returns the rounded value of val to specified precision (number of digits after the decimal point). precision can also be negative or zero (default).
Example:
echo round(113.845602277119,2); // 113.85
echo round(270.27388400703,2); // 270.27

Hi You can use number_format for this
echo number_format("113.845602277119",2)."<br>"; // 113.85
echo number_format("270.27388400703",2)."<br>"; // 270.27
or round function
echo round("113.845602277119",2)."<br>"; // 113.85
echo round("270.27388400703",2)."<br>"; // 270

The PHP round function is perfect for this kind of work, you simply pass it the number and as a 2nd parameter pass it how many numbers to round to
You can view the documentation here http://php.net/manual/en/function.round.php
round(270.27388400703, 2)
round(113.845602277119, 2)

Related

PHP expanding float value unexpectedly [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 3 years ago.
Am having an issue where PHP expands the float value e.g. 241.09 becomes 241.0899999999. The issue is, the expanded value is included in a signature, thus the expansion is causing my signature to have a mismatch when matching with the actual data which has the original unexpanded form. How do I prevent the rounding off? My code section is as below:
round(floatval($resultParams["AvailableFunds"]), 2)
Somehow, even after applying the round function, the expansion still occurs. How do I prevent that??
It's caused by the PHP Floating point precision:
Floating point numbers have limited precision.
A solution may be to use only integer, e.g. save the float 123.45 as 12345 and when you need to use display it divide it by 100 and pass it to the number_format function:
$myNumView = number_format($myNum/100, 2, '.', '')+0;
By doing this, number_format returns a string formatted as 1234567.89, then by doing +0 PHP converts it to float (due to the PHP Type Juggling) and removes the rightmost 0 in the decimal part of the number:
$a = '35';
$b = '-34.99';
echo $myNum = ($a + $b);
echo '<br>';
echo $myNumView = number_format($myNum, 4, '.', '')+0;
returns:
0.009999999999998
0.01
And also, why does you get AvailableFunds from a string with floatval? It seems that AvailableFunds is a string containing the amount of fund and other text. I think this is a bad implementation on how saving the fund amount. It's better to save the value as is in a dedicated field as float.

PHP 7 intdiv() vx floor or custom type cast

I am looking PHP 7 new Additions in order to improve my skills, i want to know what exactly the difference between the intdiv() vs floor() or custom type cast
for example
echo (int) (8/3); // 2
echo floor((8/3)); // 2
echo intdiv((8/3)); // 2
what exactly the reason for this function to add in newer version of PHP.
(int) casts the value to int whereas floor() keeps a float as a float. You used positive numbers in your example, but the difference is in negative numbers.
intdivwas designed to keep int after division of 2 ints.
echo (int) (-8/3); // -2
echo floor(-8/3); // -3
echo intdiv(-8,3); //-2
There is a different in how they behave in terms of rounding.
divint() is more intelligent, it always knows if it supposes to round up or down.
floor()
With floor(), you will always round the value lover so:
3.33333 becomes 3
-3.33333 becomes -4
Which is often not what you intend.
divint()
divint will round to the closest number:
3.33333 becomes 3
-3.33333 becomes -3
Casting to (int)
Casting float/double to a int will perform similary like divint. So you can use:
(int)(10/3) returns 3
(int)(-10/3) returns -3
In general all these three you mentioned works similar as of your example but intdiv() will give you more accurate result while working extremely large set of numbers
here is example you can see.
echo PHP_INT_MAX; // 9223372036854775807
echo (int)(PHP_INT_MAX/2); // 4611686018427387904
// here you can look the ending number
echo floor(PHP_INT_MAX/2); // 4.6116860184274E+18
// here you can see floor will return scientific notation for larger numbers
echo intdiv(PHP_INT_MAX,2); // 4611686018427387903
// you can compare the result return by (int) cast
intdiv() always give you positive number or in other word intdiv() let you know how many times you can divide evenly
Another example developer always use Modulus Operator in order to get remainder but intdiv() will always return you positive numbers and let you know how many times you can divide evenly.
echo (5 % 2) // 1
echo intdiv(5, 2) // 2
Hope this good enough to understand the difference among all 3 of them..

php round float number

I have read the documentation and have clear idea of round but i didn't find useful information to solve the problem.
The problem is i have float number which is let say 1.09 and i want to display it 2 instead of 1. if we use round function it display 1. Help me solve this problem.
MORE DETAILS...
$TotalPaidRemaining=1090;
$monthly_installments=1000;
$MakingNumberOfMonths=$TotalPaidRemaining/$monthly_installments;
echo round($MakingNumberOfMonths, 0, PHP_ROUND_HALF_UP);// it display 1. i want it display 2..
What i want is if the value after decimal point is greater than 0. For example 0.01. I want to consider it as 1.
Hope i am clear at my question.
Use the ceil() function instead.
$number = ceil(0.1); // $number will be 1
From the documentation :
Returns the next highest integer value by rounding up value if necessary.
You can use the ceil() php function instead of round(). It will round up your values. Docs: http://php.net/manual/en/function.ceil.php
Example:
ceil(1.09); // return 2
You could use ceil($yourNumber), which will round the number to its next higher integer.
Or you could use round($yourNumber + 0.499999999999999).
Or you could use floor($yourNumber + 1), which rounds the number to its previous highest integer.

Formatting Numbers with PHP [duplicate]

This question already has answers here:
Print numeric values to two decimal places
(6 answers)
Closed 11 months ago.
I'm saving numbers in MySQL using double(10,2).
The numbers are getting saved like:
456.2
232.20
764
On output, I want to force 2 decimals and add the necessary trailing zeros (currency).
Here is the function I'm using and it isn't working.
function format_currency_form($get_money) {
$money_output = abs(number_format($get_money, 2, '.', ''));
return $money_output;
}
(I'm using ABS because I want the value to display as a positive number regardless of its true value in the db)
Here is the code block used to output the data:
<?php echo format_currency_form($row_rs_data['trans_amount']); ?>
No errors getting thrown and no trailing zeros...
Any ideas?
Thanks
Brett
If you are dealing with currency try to use moneyformat
http://php.net/manual/en/function.money-format.php
money_format('%.2n', $number)
In your case the abs should be done in this way:
$number=-11.44;
$money_output = money_format('%.2n', abs($number));
echo $money_output;
If you are dealing with currencies (I think so) money_format gives you a lot of options.
Use sprintf to output formatted strings.
echo sprintf("%.2f", format_currency_form($blah_blah));

Variable and Value Types

I have a simple question about variable type in php. I have two values in my array:
$row['DS'] // type :float (with one decimal like 12.2)
$row['TC'] // type :float (with one decimal like 24.2)
What I'm actually try to do in the make the calculation below:
$row['TC'] / $row['DS'] // $row['DS'] need to be as integer (without point,like 12)
and the result should be with two decimal like (2.32). I tried to do it in that way
$DSF = number_format($row['DS'],0);
$ConF = $row['TC'] / $DSF ;
echo number_format($conF,2);
but it returns the wrong result. for example :
$row['DS'] = 59,009.3 ---> after change the format is change to 59,009
$row['TC'] = 190.0
$ConF = 190.0 / 59,009
it should be 000.223 (something around this number ) and i expect to get 0 (after i change the format using number_format($conF,2) but instead of this the program return me the number 3.22
What am I doing wrong?
The function number_format() is used to format numbers to a comma style representation, not to actually round numbers to what you want.
The function you are looking for is round which returns a float to a specified number of decimal places.
For example:
$yourVar=round($row['TC']/$row['DS'],2);
This means that $yourVar will be the value of the division rounded to two decimal places.
You should use the number_format() function only to display human-friendly numbers at the end.
You can use type casting to convert $row['DS'] to integer right in your calculations, for e.g.:
$row['TC'] / (int)$row['DS']
or
$row['TC'] / intval($row['DS'])

Categories