2014-05-25 23 views
-3

我正在構建的當前應用程序需要讓用戶輸入值「3,040,400.00」。在PHP中添加逗號和點分隔值

我注意到PHP不知道如何使用該格式添加或減去值?

我該如何執行此操作,同時請記住用戶將輸入如上格式化的值?

例如:

$a = '3,040,400.00'; 
$b = '23,949.00'; 

echo $a - $b; // returns -20 
+3

上的值做數學之前刪除任何逗號,例如與'str_replace'。 – deceze

+0

數字在這個意義上沒有「格式」....字符串可能代表格式化的數字值,但不是它們自己的數字 –

+0

在提交到數據庫之前刪除所有逗號。您可以隨時重新格式化它們。 – Strawberry

回答

1

你應該僅僅是爲了使用str_replace()首先刪除字符串內的逗號。你不能直接對它們進行算術運算。然後在正確轉換它們之後,最後可以使用number_format()。考慮下面這個例子:

$a = '3,040,400.00'; 
$b = '23,949.00'; 
$a = (float) str_replace(',', '', $a); 
$b = (float) str_replace(',', '', $b); 
$total = $a - $b; 
echo number_format($total, 2, '.', ','); // should output : 3,016,451.00 

Fiddle

0
$a = str_replace(",","",$a); 

同樣對於B

輸出自己的價值觀,你可以使用PHP函數number_format()http://www.php.net/manual/en/function.number-format.php

+0

這讓我想起了,但結果需要以逗號和點的形式顯示在同一個表單中。 – Cosmin

+2

@Cosmin您只能在實際顯示值時使用任何舍入/格式化數字 –

+0

使用此php函數輸出格式。 http://www.php.net/manual/en/function.number-format.php – newBee