如何在 PHP 中为数字添加逗号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4582562/
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-25 13:33:29  来源:igfitidea点击:

How can I add commas to numbers in PHP

php

提问by Ahmad Fouad

I would like to know how can I add comma's to numbers. To make my question simple.

我想知道如何在数字中添加逗号。为了使我的问题简单。

I would like to change this:

我想改变这一点:

1210 views

To:

到:

1,210 views

and :

和 :

14301

to

14,301

and so on for larger numbers. Is it possible with a php function?

对于更大的数字,依此类推。是否可以使用 php 函数?

回答by andrewk

from the php manual http://php.net/manual/en/function.number-format.php

来自 php 手册http://php.net/manual/en/function.number-format.php

I'm assuming you want the english format.

我假设你想要英文格式。

<?php

$number = 1234.56;

// english notation (default)
$english_format_number = number_format($number);
// 1,235

// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56

$number = 1234.5678;

// english notation with a decimal point and without thousands seperator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57

?>

my 2 cents

我的 2 美分

回答by Kausha Mehta

The Following code is working for me, may be this is helpful to you.

以下代码对我有用,可能对您有帮助。

$number = 1234.56;

echo number_format($number, 2, '.', ',');

//1,234.56

//1,234.56

回答by kelv

 $number = 1234.56;

//Vietnam notation(comma for decimal point, dot for thousand separator)

 $number_format_vietnam = number_format($number, 2, ',', '.');

//1.234,56

回答by Geoff Kendall

Often, if a number is big enough to have commas in it, you might want to do without any numbers after a decimal point - but if the value you are showing could ever be small, you would want to show those decimal places. Apply number_format conditionally, and you can use it to both add your commas and clip off any irrelevant post-point decimals.

通常,如果一个数字大到足以在其中包含逗号,您可能希望在小数点后没有任何数字 - 但如果您显示的值可能很小,您可能希望显示这些小数位。有条件地应用 number_format,您可以使用它来添加逗号并剪掉任何不相关的后点小数。

if($measurement1 > 999) {
    //Adds commas in thousands and drops anything after the decimal point
    $measurement1 = number_format($measurement1);
    }

Works well if you are showing a calculated value derived from a real world input.

如果您显示的是从真实世界输入中导出的计算值,则效果很好。