How to replace dot with comma in price format in php

227

I have a price format like 1.100.000 Now I want to replace all dots with comma so it should look like this- 1,100,000. To achieve this I tried this code-

<?php
$number=1.100.000;
$number=str_replace('.',',',$number);
?>

But it is not working. Can any one help.?

820

Answer

Solution:

Missing the quotes.Try this -

$number="1.100.000";
$number=str_replace('.',',',$number);
var_dump($number);

OutPut -

string(9) "1,100,000"
628

Answer

Solution:

To make it a little bit more robust, you can only replace the dot only if it has 3 following numbers, so it does not replace cents. Try:

$number = "1.100.000.00";
$number = preg_replace('/\.(\d{3})/', ',$1', $number);
var_dump($number);

OutPut -

string(12) "1,100,000.00"
912

Answer

Solution:

You can use RegExp

preg_replace('/\./', ',', $number);

This would replace all '.' dots with ','.

214

Answer

Solution:

Your function is not working because

$number=1.100.000;  
var_dump($number);

Parse error: syntax error, unexpected '.000' (T_DNUMBER)

is not a string andstr_replace() only works onstring value

So you have to do this

$number="1.100.000";  (type = string)
107

Answer

Solution:

The best way is number_format() function. https://www.php.net/manual/en/function.number-format.php

Follow this exemple:

$number = 1234.56;

// english notation (default)
$english_format_number = number_format($number);
// 1,235

// French notation with thousands separator
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56

$number = 1234.5678;

// english notation without thousands separator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57

People are also looking for solutions to the problem: Error in image uploading and renaming in php

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.