-2

I know it may be a silly one and it may be duplicate question as well, but I can't find any proper question posted before(may be its my incapability)

I have a value fetched from DB... its say like

4.5   which should be 4.500
0.01  which should be 0.010
11    which should be 11.000

How can I achieve this in PHP?

Saswat
  • 12,320
  • 16
  • 77
  • 156

6 Answers6

7

Simply format it with sprinft to make it a floating point number to 2 decimal places.

echo sprintf("%.2f", 4.5);

https://eval.in/378771

If you change the 2 to a 3 you will get your format you've listed.

echo sprintf("%.3f", 4.5) . PHP_EOL;
echo sprintf("%.3f", 0.01) . PHP_EOL;
echo sprintf("%.3f", 11) . PHP_EOL;

https://eval.in/378773

ʰᵈˑ
  • 11,279
  • 3
  • 26
  • 49
4

php.net/number_format

number_format(4.5,2);

Geoff Atkins
  • 1,693
  • 1
  • 17
  • 23
3

Use the function number_format

Trailing zeros to the right of a decimal point is not supported in PHP. You need to format the number to string.

$value = number_format($value,3);

GiriB
  • 166
  • 5
1

Modern way is to use NumberFormatter which formats numbers according to set locale.

$fmt = new NumberFormatter('en-US', NumberFormatter::DECIMAL);
$fmt->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, 3);
$fmt->format(1234567.891234567890000);
venca
  • 1,196
  • 5
  • 18
1

If You use mysql then Use FORMAT function like SELECT FORMAT(4.5,4)

Mukesh Kalgude
  • 4,814
  • 2
  • 17
  • 32
1

also str_pad(4.5,STR_PAD_RIGHT) for more http://php.net/manual/zh/function.str-pad.php

Gary Liu
  • 13,758
  • 1
  • 17
  • 32