Reputation: 566
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.?
Upvotes: 0
Views: 18233
Reputation: 182
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
Upvotes: 2
Reputation: 701
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"
Upvotes: 4
Reputation: 4224
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 and str_replace()
only works on string
value
So you have to do this
$number="1.100.000"; (type = string)
Upvotes: 1
Reputation: 360
You can use RegExp
preg_replace('/\./', ',', $number);
This would replace all '.' dots with ','.
Upvotes: 1
Reputation: 31749
Missing the quotes.Try this -
$number="1.100.000";
$number=str_replace('.',',',$number);
var_dump($number);
OutPut -
string(9) "1,100,000"
Upvotes: 9