Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP, Format Number to have always have 2 decimal places

In PHP I have decimal numbers that may or may not have trailing zeros.

For example

 1
 1.1
43.87

How do I make sure that all these numbers have exactly two decimal places like this:

 1.00
 1.10
43.87
like image 927
smack-a-bro Avatar asked Sep 19 '13 15:09

smack-a-bro


People also ask

How can I get only 2 decimal places in PHP?

$twoDecNum = sprintf('%0.2f', round($number, 2)); The rounding correctly rounds the number and the sprintf forces it to 2 decimal places if it happens to to be only 1 decimal place after rounding. Save this answer.

How do you keep 2 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.

What does Number_format do in PHP?

PHP | number_format() Function. The number_format() function is an inbuilt function in PHP which is used to format a number with grouped thousands. It returns the formatted number on success otherwise it gives E_WARNING on failure.

How do you make a float to 2 decimal places?

The %. 2f syntax tells Java to return your variable (value) with 2 decimal places (. 2) in decimal representation of a floating-point number (f) from the start of the format specifier (%).


1 Answers

You should use number_format():

number_format(1.1, 2);
like image 96
Carlos Avatar answered Oct 19 '22 03:10

Carlos