How to replace dot with comma in price format in php

ぃ、小莉子 提交于 2019-12-11 20:24:53

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!