用逗号代替点的十进制数(php 和 sql)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2002571/
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
Decimal number with comma instead of point (php and sql)
提问by sk.
I'm doing a little application of adding prices and decimals. Points are normal to use with decimals, but how can I write decimal number with comma as input (543,35 instead of 543.35) and then maybe change it with point to the database (mysql)? Then print it back form the database with the comma. Reason is that comma (,) is more used in Finland than point (.) when write decimal numbers.
我正在做一个添加价格和小数的小应用。点与小数一起使用是正常的,但是我如何用逗号写十进制数作为输入(543,35 而不是 543.35),然后可能会改变它指向数据库(mysql)?然后用逗号将其从数据库中打印回来。原因是在写十进制数时,逗号 (,) 在芬兰使用得比点 (.) 多。
Thank you very much!
非常感谢!
Samuel
塞缪尔
回答by Stefan Gehrig
$input = '5,50';
$output = str_replace(',', '.', $input);
var_dump($output); // string(4) "5.50"
$number = (float)$output;
var_dump($number); // float(5.5)
回答by mirezus
you need not do anything in the sql end. you want to format the decimal value in php (this assumes php4/php5): Set the third parameter $dec_point to ','
你不需要在 sql 端做任何事情。您想在 php 中格式化十进制值(假设为 php4/php5):将第三个参数 $dec_point 设置为 ','
// string number_format ( float $number , int $decimals , string $dec_point , string $thousands_sep )
<?php
$number = 1234.56;
// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56
$number = 1234.5678;
// english notation without thousands seperator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57
?>
source: http://php.net/manual/en/function.number-format.php
来源:http: //php.net/manual/en/function.number-format.php
Cheers!
干杯!
回答by Nicolas
the PHP number_formatfunction is what you need :
PHP number_format函数正是您所需要的:
number_format(5.50, 2, ',');
...should do the trick.
...应该可以解决问题。
回答by Kevin Devine
As it's been said, it's best to save the value as a float and then format for display. As an alternative to the previously suggested number_format(), you could try money_format() http://us.php.net/manual/en/function.money-format.phpIt doesn't work in a windows environment though if that is important to you.
如前所述,最好将值保存为浮点数,然后格式化以进行显示。作为先前建议的 number_format() 的替代方法,您可以尝试 money_format() http://us.php.net/manual/en/function.money-format.php它在 Windows 环境中不起作用,但如果那样的话对你很重要。
回答by nikc.org
No, using comma as a decimal separator for arithmetic operations is not supported. Filter your input and replace the comma with a period, then format your output as you wish.
不,不支持使用逗号作为算术运算的小数分隔符。过滤您的输入并用句点替换逗号,然后根据需要格式化输出。

