问题
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.?
回答1:
Missing the quotes.Try this -
$number="1.100.000";
$number=str_replace('.',',',$number);
var_dump($number);
OutPut -
string(9) "1,100,000"
回答2:
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"
回答3:
You can use RegExp
preg_replace('/\./', ',', $number);
This would replace all '.' dots with ','.
回答4:
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)
来源:https://stackoverflow.com/questions/29740233/how-to-replace-dot-with-comma-in-price-format-in-php