[英]How do I preserve leading and trailing zeros in PHP?
我正在尝试从数据库中读取一个数字并将其写入一个excel文件,但是我无法保持前导零和尾随零。 当我检查它时,我能够看到在读取数据时,PHP将其视为数字而不是字符串。 我尝试过类型转换和使用空字符串连接值。 但是,以下代码
<?php
$a = (string) 180961.65000;
echo $a;
?>
得到下面的输出
180961.65
我将如何保留零?
你可以试试看
$number = 180961.65000;
$string = sprintf("%f",$number);
echo $string;
//result:180961.650000
请使用引号将$ a标识为字符串(如果可能,还请使用带回声的引号):
$a = "180961.65000";
echo "$a";
您需要为此的number_format
$a = "180961.650000000";
$total_len = strlen($a);
$dec_pos = strpos($a, ".");
$diff = $total_len - ($dec_pos +1);
$a = number_format($a,$diff);
$a = str_replace(",", "", $a);
echo $a;
尝试把
<?php
$a = (string) "180961.65000";
echo $a;
?>
在使用变量时,数据类型会以某种不清楚的方式自动更改。
因此,我建议在变量仍然是字符串的同时显式保留前导和尾随数字。 然后在变量变为数字后再添加它们。 它可能看起来很丑陋,但对于任意数量的零,它都是灵活的。
像这样:
// Example number, assume it was received by database
$input = "00018096.16500000";
// Get the leading and trailing zeros as string.
preg_match("/^0+/", $input, $leading);
preg_match("/0+$/", $input, $trailing);
// Mark if there is a decimal point.
$hasDigit = strpos($input, ".") !== false;
// Only for here: force the input to become a number, thus removing all trailing and leading zeros.
$input = 1 * $input;
// Now add the leading and trailing zeroes again and turn the variable back to a string.
$saveOutput = $input . "";
if (count($leading) > 0) {
$saveOutput = $leading[0] . $saveOutput;
}
// If the number is not a float with decimal point, don't add the trailing zeros as they are still there in the integer number.
if (count($trailing) > 0 && $hasDigit) {
$saveOutput = $saveOutput . $trailing[0];
}
// Show result
echo $saveOutput;
// --> Result:
// 00018096.16500000
注意,我将变量saveOutput
因为您确定它是一个字符串,并且不会像input
一样更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.