【问题标题】:Decimal number with comma instead of point (php and sql)用逗号代替点的十进制数(php 和 sql)
【发布时间】:2010-01-04 21:59:55
【问题描述】:

我正在做一些添加价格和小数的应用程序。点与小数一起使用是正常的,但我怎样才能用逗号写十进制数作为输入(543,35 而不是 543.35),然后也许用指向数据库(mysql)的点来改变它?然后用逗号将其从数据库中打印出来。原因是在芬兰写十进制数时,逗号 (,) 比点 (.) 使用得更多。

非常感谢!

塞缪尔

【问题讨论】:

  • 如果您以多种格式呈现,这是一个呈现问题,因此最好在 PHP 中处理。否则,您可以从 SQL 格式化值。

标签: php sql


【解决方案1】:
$input  = '5,50';
$output = str_replace(',', '.', $input);
var_dump($output); // string(4) "5.50"
$number = (float)$output;
var_dump($number); // float(5.5)

【讨论】:

    【解决方案2】:

    你不需要在 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
    
    ?>
    

    来源: http://php.net/manual/en/function.number-format.php

    干杯!

    【讨论】:

    • 谢谢!现在我可以用逗号 12,50 而不是 12.50 来介绍数字(芬兰语键盘更容易),这样它就可以用小数识别?
    • 对。您只需要担心前端的数字格式,让 MySQL 照常存储。无论您如何显示,底层数字仍然是相同的。
    【解决方案3】:

    PHP number_format 函数就是您所需要的:

    number_format(5.50, 2, ',');
    

    ...应该可以解决问题。

    【讨论】:

    • 糟糕,这实际上不是……我的错。 (另一方面,我总是很惊讶地看到人们评论错误的答案却没有提供正确的答案。继续前进,你们给社区带来了很多:)
    【解决方案4】:

    如前所述,最好将值保存为浮点数,然后格式化显示。作为之前建议的 number_format() 的替代方法,您可以尝试 money_format() http://us.php.net/manual/en/function.money-format.php 如果这对您很重要,它在 Windows 环境中不起作用。

    【讨论】:

    • 哎呀,我想我读你的问题太快了......你不需要货币格式,对吗?
    • 是的,不需要货币格式。我还在寻找什么,是否有可能用逗号输入十进制数?我不知道能否以正确的方式提出我的问题?
    【解决方案5】:

    不,不支持使用逗号作为算术运算的小数分隔符。过滤输入并将逗号替换为句点,然后根据需要格式化输出。

    【讨论】:

      猜你喜欢
      • 2015-09-20
      • 2017-10-06
      • 1970-01-01
      • 2018-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多