I have came across the php rounding decimal values by using:
The round() function rounds a floating-point number.
To round a number UP to the nearest integer, look at the ceil() function.
To round a number DOWN to the nearest integer, look at the floor() function.
I have an example of dividing 1000/13 which when we use
round(1000/13, 2) will give you 999.98 and then i will use ceil to round it to 1000.
Now, my value is 925.6 which has to be divided by 11 and I tried with the
round(925.6/11, 2) which will give 84.15, then if u multiply this with 11(84.15 * 11)then you will get 925.56 . Now how can achieve the exact decimal if any decimal input.
Rounding-off a Double or Float using
round()
,ceil()
orfloor()
all have one thing in Common and that is: by using them you are subscribing to losing the Precision of your Data. This means; once the die is cast, you cannot get the Original value again.... it is that simple:
If you want to retain both the Truncated and the Original Values, you have to do it differently.... You may need to keep 2 Variables or simply put your Variables in an Array. A Simple example would demonstrate this even better:
<?php
$num = (925.6/11);
// STORE THE ORIGINAL & ROUNDED VALUES IN AN ARRAY (IN CASE YOU NEED BOTH)
$arrNumbers = [
'original' => $num,
'rounded' => round($num, 2),
];
// NOW; FOR YOUR MULTIPLICATIONS:
$original = $arrNumbers['original'] * 11;
$broken = $arrNumbers['rounded'] * 11;
var_dump($original); //<== float 925.6
var_dump($broken); //<== float 925.65 :: ADDED AN EXTRA 0.05 (BOGUS, HUH?)
var_dump($arrNumbers); //<== array (size=2) 'original' => float 84.1454545455 'rounded' => float 84.15
UPDATE: NUMERATOR AS A VALUE FROM FORM-FIELD.
<?php
// ASSUME THE VALUE OF THE NUMERATOR IS: 925.6
$numerator = htmlspecialchars(trim($_POST['some_field']));
// AND THE DENOMINATOR IS NOW SOMETHING LIKE MONTH 11 AS IN: 11.0000
$denominator = 11.0000;
// NO PROBLEMS STILL...
$num = ($numerator/$denominator);
// STORE THE ORIGINAL & ROUNDED VALUES IN AN ARRAY (IN CASE YOU NEED BOTH)
$arrNumbers = [
'original' => $num,
'rounded' => round($num, 2),
];
// NOW; FOR YOUR MULTIPLICATION,
// TO GET THE STARTING VALUES BACK DO:
$original = $arrNumbers['original'] * 11;
$broken = $arrNumbers['rounded'] * 11;
var_dump($original); //<== float 925.6
var_dump($broken); //<== float 925.65 :: ADDED AN EXTRA 0.05 (BOGUS, HUH?)
var_dump($arrNumbers); //<== array (size=2) 'original' => float 84.1454545455 'rounded' => float 84.15
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.