Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show a number to two decimal places

What's the correct way to round a PHP string to two decimal places?

$number = "520"; // It's a string from a database  $formatted_number = round_to_2dp($number);  echo $formatted_number; 

The output should be 520.00;

How should the round_to_2dp() function definition be?

like image 735
Rich Bradshaw Avatar asked Dec 19 '10 15:12

Rich Bradshaw


People also ask

How do you convert a number to two decimal places?

Rounding a decimal number to two decimal places is the same as rounding it to the hundredths place, which is the second place to the right of the decimal point. For example, 2.83620364 can be round to two decimal places as 2.84, and 0.7035 can be round to two decimal places as 0.70.

How do I bring to 2 decimal places in Excel?

On the Formulas tab, under Function, click Formula Builder. In number, type the number you are rounding up. In num_digits, type 0 to round the number up to the nearest whole number. In number, type the number you are rounding down.

How do I format to 2 decimal places in Word?

Click the Table Tools' Layout tab, select Data and then click Formula. Click the Number Format menu and select 0.00 for two decimals.


1 Answers

You can use number_format():

return number_format((float)$number, 2, '.', ''); 

Example:

$foo = "105"; echo number_format((float)$foo, 2, '.', '');  // Outputs -> 105.00 

This function returns a string.

like image 159
Codemwnci Avatar answered Oct 01 '22 18:10

Codemwnci