want to display exactly 2 digits after floating point - php

I want to convert floating value of 8 digits after floating point in to 2 digits after floating point ..
Eg. $a = 2.200000 ==> 2.20
I am using round function of php. Problem with round is if my number is 2.200000 it converts number in 2.2 . I want output as 2.20
Can any one suggest the possible way?
Actual code
$price = sprintf ("%.2f", round(($opt->price_value + ($opt->price_value * $this->row->prices[0]->taxes[0]->tax_rate)), 2));
i want out put like if my floating number is 2.2000000. then it should return me 2.20. but right now it is returning me 2.2

This does what I think you are asking for:
<?php
$a = 2.20032324;
$f = sprintf ("%.2f", $a);
echo "$a rounded to 2 decimal places is '$f'\n";
$a = 2.2000000;
$f = sprintf ("%.2f", $a);
echo "$a rounded to 2 decimal places is '$f'\n";
results:
[wally#lenovoR61 ~]$ php t.php
2.20032324 rounded to 2 decimal places is '2.20'
2.2 rounded to 2 decimal places is '2.20'
I added two test cases

i was working on it :D
$number='49.099998479854654656516198498465465465465';
function pure_decimal($number){
if(is_numeric($number) and floor($number)!=$number){
//decimal detected
$explode=explode('.',$number);
$first_no=$explode['0'];
$second_no=$explode['1'];
$get_only_two=substr($second_no,0,2);
$final_no=$first_no.'.'.$get_only_two;
$final_no=($final_no*1);
}else{
//normal
$final_no=$number;
}
return $final_no;
}
//result is 49.09
regards.

try $val = round($a * 100)/100;

Try the below code, You can get your result.
$a = 2.200000;
echo number_format((float)$a,2,'.','');

Related

Round second digit after decimal to produce nice number

Need to round 30.61 to 30.60, Any built-in function for PHP to do this ?
If I understand your desired output correctly, that you only want to round the second decimal point, you can round with 1 decimal presicion, then use numer_format() to ensure you get the correct number of decimals.
$num = 30.61;
echo number_format(round($num, 1), 2);
round() documentation
number_format() documentation
Live demo
you can do this
$num = 3.61;
/*round to nearest decimal place*/
$test_number = round($num,1);
/* ans :3.6
format to 2 decimal place*/
$test_number = sprintf ("%.2f", $test_number);
/* ans : 3.60 */

is possible to less float values..?

$quantity = 20;
$product_rate = 66.79;
$total = $quantity * $product_rate;
echo $total;
Output is showing 1335.8000000000002
is there possible to show 1335.8 using php..?
You can use the number_format() function like this:
$firstNum = 1335.8000000000002;
$number = number_format($firstNum, 1, '.', '');
echo $number;
outputs:
1335.8
more on number_format() here: http://php.net/number-format.
You can also multiply the number by 10, then use intval() to convert it to an integer (that way stripping out the decimals) and then divide by 10 like this:
$firstNum = 1335.8000000000002;
$number = 10 * intval($firstNum)/10;
echo $number;
outputs:
1335.8
Note: when using the methods above there will be no rounding, for rounding you would use something like this:
$number = round($firstNum, 1);
echo $number;
which in this case also outputs:
1335.8
Do you really use these variable values? I'm using PHP7 and the output for your given values is 1335.8. If you do a manual calculation it is the same result. It should be 1335.8. Anyway if you need to roundup the value you can use below.
round($total,1);
Please refer the below link and you will be able to grab more details.
http://php.net/manual/en/function.round.php
Because how floating point numbers work, they cannot represent every numbers exactly, so approximations are made.
The closest representation of 20 is 20, it can represent 20 exactly, but 66.79 for instance is approximated to 66.7900000000000062527760746889, that times 20 is 1335.800000000000125055521493778 that again cannot be represented and is approximated to 1335.80000000000018189894035459.
Depending on how you choose to print this number, it may round different ways, in your case for some reason you decided to print 13 decimal places so it rounded to 1335.8000000000002, but if you print only 1 or 2 decimal places it will print as 1335.8 or 1335.80. Just be mindful about that when printing floating point numbers, you may want to specify how many decimal places are relevant to you. For that, use number_format().
Example:
echo number_format($number, 2); // prints 2 decimal places
You can do this simply using echo echo round($total, 1) instead of doing round($total)

decimal point and zero are removed after adding two equal floating numbers in php

I am trying to solve a problem on HackerRank and its not making any sense.
<?php
$d = 4.0;
$f = 4.0;
$sum = $d + $f;
echo $sum;
?>
I need an output of 8.0 but its giving output of 8. Am I missing something?
Float values with decimal part equal to zero gets printed without the decimal part. If you need to force certain numbers of decimal places, use number_format().
In your case: echo number_format($sum, 1);

PHP. result of the subtraction of two floating point numbers

For example...
$aa = 10694994.89;
$bb = 10696193.86;
$ab = $aa - $bb;
// result is:-1198.9699999988 not the -1198,97
But in this exampe:
$cc = 0.89;
$dd = 0.86;
$cd = $cc - $dd;
//Result is: 0.03
Why the difference in to examples? Lacks precision?
None of the numbers in your code can be expressed exactly in binary floating point. They have all been rounded somehow. The question is why one of the results has been (seemingly) rounded to two decimal digits and not the other. The answer lies in the difference between the precision and accuracy of floating point numbers and the precision PHP uses to print them.
Floating point numbers are represented by a significand (or mantissa) in the range [1, 2), which is scaled by multiplying it by a power of two. (This is what the "floating" in floating point means). The precision of the number is determined by the number of digits in the significand. The accuracy is determined by how many of those digits are actually correct. See: How are floating point numbers stored in memory? for more details.
When you echo floating point numbers in PHP, they are first converted to string using the precision configuration setting, which defaults to 14. (In Zend/zend_operators.c)
To see what is really going on, you have to print the numbers using a larger precision:
$aa = 10694994.89;
$bb = 10696193.86;
$ab = $aa - $bb;
printf ("\$aa: %.20G\n", $aa);
printf ("\$bb: %.20G\n", $bb);
printf ("\$ab: %.20G\n\n", $ab);
$cc = 0.89;
$dd = 0.86;
$cd = $cc - $dd;
printf ("\$cc: %.20G\n", $cc);
printf ("\$dd: %.20G\n", $dd);
printf ("\$cd: %.20G\n", $cd);
Output:
$aa: 10694994.890000000596
$bb: 10696193.859999999404
$ab: -1198.9699999988079071
$cc: 0.89000000000000001332
$dd: 0.85999999999999998668
$cd: 0.030000000000000026645
The initial numbers have a precision of about 16 to 17 digits. When you subtract $aa-$bb, the first 4 digits cancel each other out. The result, (while still having a precision of about 16 to 17 digits), is now only accurate to about 12 digits. This lower accuracy shows up when the results is printed using a 14-digit precision.
The other subtraction ($cc-$dd) loses only a single digit of accuracy, which isn't noticable when printed with a 14-digit precision.
This should work for you:
(You have to round your result!)
$aa = 10694994.89;
$bb = 10696193.86;
echo $ab = round($aa - $bb, 2);

Error With Using (int) and (double) together to Cut off Decimals

When I am using (int) with (double) some times it is not working correct.
Look At The PHP Code Example:
I Need To LEAVE 2 Decimals And REMOVE Other...
I Know number_format(); function But I Cannot Use It. Because It Is Rounding Number
number_format(24.299,2);
Output: 24.30
I Need: 24.29
<?php
$str="158.2";
echo (double)$str; // Output: 158.2
echo (double)$str*100; // Output: 15820
echo (int)((double)$str*100); // Output: 15819 <-WHY? It Must To Be 15820, Why 15819?
echo ((int)((double)$str*100)/100); // Output: 158.19
?>
I need To leave two decimals in the number and cut other WITHOUT rounding.
Because of floating point precision (see for example this question: PHP - Floating Number Precision), 158.2 * 100 is not exactly 15820 but something like 15819.99999999.
Now (int) is for type conversion, not for rounding, and any digits after the point are cut of.
I need To leave two decimals in the number and cut other WITHOUT rounding.
This is easy:
number_format($str, 2);
Update
number_format does round, so it is a bit more complicated:
bcmul($str,100,0)/100
bcmul multiplies with arbitrary precision, in this case 0. Results:
bcmul(158.2,100,0)/100 == 158.2
bcmul(24.299,100,0)/100 == 24.29
This doesn't answer the question of why that happens (it could be a precision bug), but to solve your problem, try using $foo = sprintf("%.2f", (float)$str);.
Example:
$str = "158.2";
$num = (double)$str;
print sprintf("%.2f", $num);
EDIT: Infact, yes, this is a precision issue. (in C++) by printing 158.2 to 20 decimal places, I get the output of "158.19999999999998863132". This is an inherent problem with floating point/double precision values. You can see the same effect by using echo sprintf("%.20f", $var); in PHP.
First off, PHP is a language that allows you to type juggle. Which means you do not need the (int) or the (double) to do what you're trying to do.
<?php
$str="158.2"; //could also do $str = 158.2
echo $str; // Ouput: 158.2
echo $str * 100; //Output: 15820
echo number_format($str, 2); //Output: 158.20
echo number_format(($str*100)/100, 2); //Output: 158.20
?>
Use the number_format command to format your numbers how you want.
More here
Never cast an unknown fraction to integers, see the manual on http://www.php.net/manual/en/language.types.integer.php.
(int) ( (0.1+0.7) * 10 ); will result in 7, not 8 as one might expect. Casting from float to integer will always round down - and you may also want to check the operator precedence http://php.net/manual/en/language.operators.precedence.php.
Solution: calculate your fraction before you cast it. $fStr = (float) $str; $iStr = (int) $fStr;
Fixed.
function cutDecimals($number,$decimal){
$_str=(string)$number;
if(strpos($_str,".")!==false){
$dotPosition=strpos($_str,".")+1;
$_numCount=strpos($_str,".");
$_decimal=strlen($_str)-$dotPosition;
if($_decimal<$decimal) return (double)$_str;
else return (double)substr($_str,0,$_numCount+$decimal+1);
}else return (double)$_str;
}
echo cutDecimals("158.099909865",2)."<br />";
echo cutDecimals("14.02",2)."<br />";
echo cutDecimals("41.12566",2)."<br />";
echo cutDecimals("1.981",2)."<br />";
echo cutDecimals("0.4111",2)."<br />";
echo cutDecimals("144.2",2)."<br />";
echo cutDecimals("55.000000",2)."<br />";
echo cutDecimals("1456115.499811445121",2)."<br />";
?>

Categories