簡體   English   中英

如何在PHP中保留前導零和尾隨零?

[英]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

參考-http://php.net/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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM