-3

I have a full int value already with the decimals and I want to convert like this in PHP

500 -> 5,00$
 5070 -> 50,70$
 50070 -> 500,70$
 500000 -> 5.000,00$

so the format should be like this xxx.xxx.xxx.xxx,xx$

any function for that?

Sanu0786
  • 571
  • 10
  • 15
  • 2
    money_format number_format – FatFreddy Dec 12 '18 at 11:54
  • 1
    Did you do any research at all before asking? Considering that there is a php function called `money_format`, just searching for your title would have given you at least that. – M. Eriksson Dec 12 '18 at 11:54
  • @MagnusEriksson is there a local that use dot `.` as thousand separator and `,` as decimal separator for `money_format` ? – Cid Dec 12 '18 at 12:06
  • @Cid - I have no idea. But the fact that the OP didn't even mention that function or showed any attempt at all, it leads me to believe that they haven't checked. They would probably also have found the `number_format()`-function quite quickly as well. – M. Eriksson Dec 12 '18 at 12:09
  • looks like he did researches, but he forgot to mention it and to show us the code – Cid Dec 12 '18 at 12:15

2 Answers2

1

number_format() can do the job.

It works like this : string number_format(float $number, int $decimals = 0, string $dec_point = ".", string $thousands_sep = ",")

number

The number being formatted.

decimals

Sets the number of decimal points.

dec_point

Sets the separator for the decimal point.

thousands_sep

Sets the thousands separator.

In your case, that could be $myMoney = number_format($cents / 100, 2, ",", ".") . "$";

Cid
  • 14,968
  • 4
  • 30
  • 45
  • I tryed this function a couple times but seams doesn't do want I want. If I have 5006 this outputs 5.006$ and sould be 50,60$. with `number_format($number, 0, ",",".") . "$";` – Rodrigo Borba Dec 12 '18 at 12:10
  • 1
    Of course this won't, read again the code I provided. You first have to convert cents to dollar (hint, a dollar is 100 cents, hence `$cents / 100`). The second argument is the number of digit on the right side of the decimal point. – Cid Dec 12 '18 at 12:12
  • By the way, you **should** have provided that piece of code in your question. – Cid Dec 12 '18 at 12:13
0

As I see you have your money format in cents so you can do:

$prices = [
    500,
    5070,
    50070,
    500000
];
foreach ($prices as $price) {
    echo money_format("Price: %i", $price / 100);
}
Malkhazi Dartsmelidze
  • 4,783
  • 4
  • 16
  • 40
  • I need a alternative to money_format() this function doesn't work on windows servers. – Rodrigo Borba Dec 12 '18 at 12:08
  • @RodrigoBorba - https://stackoverflow.com/questions/6369887/alternative-to-money-format-function-in-php-on-windows-platform - It took about 5 seconds to find. Please always start by doing proper research... – M. Eriksson Dec 12 '18 at 12:11