将逗号更改为点,在 php 中使用小数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7461459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:43:58  来源:igfitidea点击:

Change comma to dot, working with decimals in php

php

提问by Karem

So i have some fields coming from the form. Here you can type 0.3 and it will insert 0.3 in to the database. Do you type 0,3 it will just insert "0".

所以我有一些来自表单的字段。在这里你可以输入 0.3,它会将 0.3 插入到数据库中。你输入 0,3 它只会插入“0”。

$product['protein']; // 0,3

So to this above how can i replace a comma with a dot ?

那么对于上面的问题,我如何用点替换逗号?

回答by genesis

Try PHP's function str_replace():

试试 PHP 的函数str_replace()

$product['protein'] = str_replace(',', '.', $product['protein']);

Which should be a good fit.

哪个应该很合适。

You could think to use number_format():

您可以考虑使用number_format()

number_format($value, $numberOfDecimals, $charaForDecimalPoint, $charForThousandsSeparator)

but in your case it wouldn't apply, due to the fact that your starting value ("0,3") wouldn't be recognized as a number. In fact, the decimal point for a numeric value must be a dot(".").

但在您的情况下,它不适用,因为您的起始值(“0,3”)不会被识别为数字。事实上,数值的小数点必须是一个点(“.”)。

Use number_format only if your starting value is a true number.

仅当您的起始值为真数字时才使用 number_format。

回答by Brad Morris

$product['protein'] = str_replace(",",".",$product['protein'])

For more info on the str_replace function visit: http://uk.php.net/str_replace

有关 str_replace 函数的更多信息,请访问:http: //uk.php.net/str_replace

回答by Astha

try

尝试

$product['protein'] = str_replace(",",".",$product['protein'])

回答by user3290141

$product['protein'] = str_replace(',', '.', str_replace('.', '', $product['protein']));