用逗号将数字转换为货币格式

时间:2020-09-15 08:20:31

标签: php function

我正在尝试使用功能money格式将数据库中的数字转换为money格式。 SQL查询工作正常,输出为

echo "$amount" is 800,600.00.

我尝试使用

setlocale(LC_MONETARY, 'en_US');
echo money_format('%i', $amount) . "\n";

但出现以下错误:

致命错误:未捕获错误:调用C:\ xampp \ htdocs \ loan \ en \ account \ payment.php中未定义的money_format()函数:14堆栈跟踪:#0 {main}抛出到C:\ xampp \第14行的htdocs \ loan \ zh_CN \ account \ payment.php

我的总体代码为:

<?php
include('../user/db.php');
$uploaduser = "ruxell4real";
$stmt =$conn->prepare("SELECT * FROM users WHERE username=?");
$stmt->bind_param("s", $uploaduser);
$stmt->execute();
$row = $stmt->get_result();
$result= $row->fetch_assoc();

$amount = $result['balance'];


setlocale(LC_MONETARY, 'en_US');
echo money_format('%i', $amount) . "\n";

1 个答案:

答案 0 :(得分:2)

您的输入是格式为“ 800,600.00”的字符串。该字符串不能以这种方式转换为浮点数。为此,必须删除逗号。我为此使用了一个简单的str_replace。

$amount = "800,600.00";

$floatAmount = (float)str_replace(",","",$amount);
//test
var_dump($floatAmount);  //float(800600)

然后可以使用所需的格式和相应的函数/类来输出该浮点值。

echo "number_format: ". number_format($floatAmount,2,".",","). "<br>";

$fmt = new \NumberFormatter("en_US", NumberFormatter::CURRENCY);
echo "NumberFormatter: ".$fmt->format($floatAmount) . "<br>"; 

输出:

number_format: 800,600.00
NumberFormatter: $800,600.00
相关问题