如何在 PHP 中将数字格式化为美元金额 [英] How do I format a number to a dollar amount in PHP

查看:37
本文介绍了如何在 PHP 中将数字格式化为美元金额的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将数字转换为显示美元和美分的字符串?

How do you convert a number to a string showing dollars and cents?

eg:
123.45    => '$123.45'
123.456   => '$123.46'
123       => '$123.00'
.13       => '$0.13'
.1        => '$0.10'
0         => '$0.00'

推荐答案

PHP也有money_format().

这是一个例子:

echo money_format('$%i', 3.4); // echos '$3.40'

这个函数实际上有很多选项,请转到我链接的文档查看它们.

This function actually has tons of options, go to the documentation I linked to to see them.

注意:money_format 在 Windows 中未定义.

Note: money_format is undefined in Windows.

更新:通过 PHP 手册:https://www.php.net/manual/en/function.money-format.php

UPDATE: Via the PHP manual: https://www.php.net/manual/en/function.money-format.php

警告:此函数 [money_format] 自 PHP 7.4.0 起已弃用.强烈建议不要依赖此函数.

WARNING: This function [money_format] has been DEPRECATED as of PHP 7.4.0. Relying on this function is highly discouraged.

相反,请查看 NumberFormatter::formatCurrency.

    $number = "123.45";
    $formatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
    return $formatter->formatCurrency($number, 'USD');

这篇关于如何在 PHP 中将数字格式化为美元金额的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆