2013-01-10 64 views
0

所以我有這個小問題。 我有一個表格,您可以輸入一個數字,它可以是歐洲格式,逗號作爲小數點(,)或美式小數點(。)。將數字轉換爲另一個

知道了,我該如何轉換歐洲美式格式的數字格式?美國的格式保持不變?

我試過使用這個公式,但結果是錯誤的。

$american = '12.5'; 
$european = '12,5'; 

$locale = 'it_IT.utf8'; 
setlocale ('LC_NUMERIC', $locale); 
$fmt = new NumberFormatter ($locale, NumberFormatter::DECIMAL); 
$american = $ fmt->parse($american); 
$european = $ fmt->parse($europen); 

response 

$american = 125 
$european = 12.5 

問題在哪裏?

php ver。 5.4.10

+0

您錯過了'$ europen'中的'a',無論相關與否。 – Ross

+1

$ stringFormatted = str_replace(',','。',$ inputstring);那應該不會那麼困難。那是你要的嗎? – Alex

+0

不,我想在我的應用程序中實現國際化,我希望以透明的方式轉換數字,然後將其插入到一個mysql表 – Michelangelo

回答

0

是不是更好用str_replace()代替?

+0

是的,但數字可以歐洲或美國格式,然後我使用NumberFormatter函數轉換它,數字可以是歐盟1.234.567,89或美國1,234,567.89。 – Michelangelo

2

試試下面的代碼:

$american = '12.5'; 
$european = '12,5'; 

$locale = 'en_US.utf8'; 
$fmt = new NumberFormatter ($locale, NumberFormatter::DECIMAL); 
$american = $fmt->parse($american); 

$locale = 'it_IT.utf8'; 
$fmt = new NumberFormatter ($locale, NumberFormatter::DECIMAL); 
$european = $fmt->parse($european); 

得到期望的結果?

+0

沒有相同的回答 – Michelangelo

+0

給出了什麼結果? –

+0

$ american = 125 $ european = 12.5 – Michelangelo

相關問題