Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

want to display exactly 2 digits after floating point

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

like image 456
Rukmi Patel Avatar asked May 03 '12 05:05

Rukmi Patel


People also ask

How do you print 2 digits after a decimal point?

In Python, to print 2 decimal places we will use str. format() with “{:. 2f}” as string and float as a number. Call print and it will print the float with 2 decimal places.

How do I show only 2 digits after a decimal in HTML?

parseFloat(num). toFixed(2);

How do you put two digits after the decimal point in Excel?

Select the cells that you want to format. On the Home tab, click Increase Decimal or Decrease Decimal to show more or fewer digits after the decimal point.

How do I restrict a float value to only two places after the decimal point in Javascript?

To limit the number of digits up to 2 places after the decimal, the toFixed() method is used. The toFixed() method rounds up the floating-point number up to 2 places after the decimal.


1 Answers

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

like image 53
wallyk Avatar answered Nov 14 '22 22:11

wallyk