-1

I have number:

  1. 2000
  2. 100
  3. 0.1
  4. 0.15
  5. 0.1555

But I need show these number in this format:

  1. 2,000.00
  2. 100.00
  3. 0.10
  4. 0.15
  5. 0.1555

I will never have more than 4 decimals after decimal separator. If after decimal separator are only null, I need to display 2 nulls (3. example above).

How I can format these numbers to get required format? Thank you!

EDIT: I can't use just number_format function, because with this function I can only set how many decimals will be after decimal separator, but as I wrote above - sometimes there will be 2, sometimes 4. So, if my number is 2000.0001 and I set this number_format(2000.0001, 4) output will be 2000.0001, but other number like 0.1 will output 0.1000, but I need it with 0.10 format.

RydelHouse
  • 362
  • 1
  • 4
  • 23

1 Answers1

2

First use number_format to add the commas and get 4 digits after the decimal. Then use a regular expression to remove up to 2 trailing zeroes.

$formatted = preg_replace('/0{1,2}$/', '', number_format($input, 4));

DEMO

Barmar
  • 741,623
  • 53
  • 500
  • 612