php,如果数字是整数,则添加尾随零

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

php, add trailing zeros if the number is integer

php

提问by Istiaque Ahmed

Simple maths:

简单的数学:

  $a=$b/$c; echo $a;

if $b equals to 123.00 and $c equals to 1 then $a becomes 123.

如果 $b 等于 123.00 且 $c 等于 1,则 $a 变为 123。

If $b is 123.50, $c is 1, $a is 123.50. But in the former case , I want $a to be 123.00.

如果 $b 是 123.50,$c 是 1,$a 是 123.50。但在前一种情况下,我希望 $a 为 123.00。

It is possible to test whether $a has any non-zero fraction part or not, and then add the trailing zeros as necessary.

可以测试 $a 是否有任何非零小数部分,然后根据需要添加尾随零。

But I am looking for php functions to do the same thing. Possible?

但我正在寻找 php 函数来做同样的事情。可能的?

EDIT :

编辑 :

What if I do not want the commas from number_formatthere ?

如果我不想要逗号怎么办number_format

回答by Niet the Dark Absol

Use sprintf("%0.2f",$a);. docs

使用sprintf("%0.2f",$a);. 文档

回答by Palladium

Use the number_formatfunction. If you don't want comma separators, set all four parameters of the function like so (the thousands separator is the fourth parameter):

使用该number_format功能。如果不需要逗号分隔符,请像这样设置函数的所有四个参数(千位分隔符是第四个参数):

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

回答by trainoasis

Yup, like this:

是的,像这样:

$a = 123;
$answer = number_format($a,"2");
echo $answer;