iT邦幫忙

0

php number_format 千分位問題!!!

php

Dear IT前輩們
有一個php語法問題,因資料庫撈出來的資料呈現XXXXXXXX-負數,我利用number_format語法去顯示千分位符號,不過只要ECHO出的資料是負數的,負數的符號都會被取代掉...
可以麻煩IT前輩們指教...

$test = "508224.00-";
$test = number_format($test);
echo $test;

以下是資料庫拉出來的值
65199146.00
508224.00-
0.00
64690922.00
42837177.00-
21853745.00
3710279.00-
3766647.00-
5570543.00-
8806276.00
411581.00
36523350.00-
27305493.00-
0.00
27305493.00-

fillano iT邦超人 1 級 ‧ 2017-03-09 18:05:52 檢舉
php的數字格式,負數不是把符號擺在最後的吧...
小哈 iT邦新手 4 級 ‧ 2017-03-09 18:19:40 檢舉
那是從異質系統拉過來的,就呈現在後面...
fillano iT邦超人 1 級 ‧ 2017-03-10 13:51:03 檢舉
所以你要先處理這個問題,才把東西丟給number_format阿。
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

4
bizpro
iT邦大師 1 級 ‧ 2017-03-09 20:43:15
最佳解答

用程式碼來解決異質系統的問題:

<?php
$test = "508224.00-";
$sign = 1;
if ( substr($test, -1) == "-" ) {
  $sign=-1;
}
$test = number_format((float)$test*$sign,2);
echo $test;
?>

20170310T0949補充:
直接改變值, 只有負號才相乘:

<?php
$test = "508224.00-";
if ( substr($test, -1) == "-" ) {
  $test*=-1;
}
$test = number_format($test,2);
echo $test;
?>

直接改變值, 正負號都相乘:

<?php
$test = "508224.00-";
$test*=(substr($test, -1) == "-"?-1:1);
$test = number_format($test,2);
echo $test;
?>
看更多先前的回應...收起先前的回應...
wonton iT邦高手 6 級 ‧ 2017-03-10 08:32:21 檢舉

其實簡單來說就是字串處理,如果還是想要把負數符號留在後面的話,也可以這樣

<?php
    $test = "508224.00-";
    $a = explode(".", $test);
    $test = number_format($a[0]).".".$a[1];
    echo $test;
?>
小哈 iT邦新手 4 級 ‧ 2017-03-10 14:06:40 檢舉

感謝各位大大的幫忙,剛剛試了一下wonton大 and bizpro大
Code是沒問題!!!
只是遇到的是全部都會顯示成1是不是陣列中的問題...

<table width="600" border="1.5" style="border-style:solid;">
			<tr><td height="30px" bgcolor="#B0E0E6">NAME</td><td height="30px" bgcolor="#B0E0E6">DMBTR</td></tr>
		<?
		foreach ($result["IT_FA01"] as $AAA) 
		{
		
			echo "<tr><td bgcolor='#E6E6FA'>"
			, $AAA["NAME"],"</td><td bgcolor='#E6E6FA'>",number_format(explode(".00", $AAA["DMBTR"])),"</td></tr>"; 
			
		
		echo $AAA["DMBTR"];
		}
		?>

		</table>

會顯示成以下圖片
http://ithelp.ithome.com.tw/upload/images/20170310/20089833Qq2ME2uZMP.jpg

不過ECHO印出echo $AAA["DMBTR"];
卻有整排的資料...
http://ithelp.ithome.com.tw/upload/images/20170310/20089833Rab3cnZoEe.jpg

希望IT前輩能指點小弟ˊˋ

小哈 iT邦新手 4 級 ‧ 2017-03-10 14:57:23 檢舉

感謝IT大大們提供方法,已經自行解決了:)
https://pjchender.blogspot.tw/2015/05/php.html
參考這個下去處理!!!
謝謝IT大大們^^

bizpro iT邦大師 1 級 ‧ 2017-03-10 15:15:26 檢舉

您的資料結構不對. $AAA[$DMBTR]是字串, 並非數值. explode(".00", $AAA["DMBTR"])運行的結果是陣列, 更非數值. number_format的第一個參數必須是float數值.

小哈 iT邦新手 4 級 ‧ 2017-03-10 17:37:21 檢舉

Dear bizpro大大
有 之後轉成數值就搞定了 加上切割語法就OK:)
真的很感謝...

我要發表回答

立即登入回答