2016-11-22 553 views
0

我有一個應用程序需要在運行時轉換一定數量的錢,因爲應用程序將部署在不同的國家。轉換貨幣

比方說,我有一個100美元的定價。有沒有簡單的方法將其轉換爲另一種貨幣(我基於設備的區域設置獲取)?

乾杯

+1

你意識到匯率波動,對吧? Java沒有內置任何東西來處理這個問題。 –

+0

您可以使用谷歌API:[鏈接](https://www.google.com/finance/converter?a=1&from=USD&to=INR)或歐洲央行API:[鏈接](http://www.ecb .europa.eu/stats/eurofxref/eurofxref-daily.xml)更新貨幣值 –

回答

0

我使用谷歌金融計算器爲用戶與應用互動,你可以在PHP中使用它獲取轉換的數據。

function convertCurrency($amount, $from, $to){ 
$url = "https://www.google.com/finance/converter?a=$amount&from=$from&to=$to"; 
$data = file_get_contents($url); 
preg_match("/<span class=bld>(.*)<\/span>/",$data, $converted); 
$converted = preg_replace("/[^0-9.]/", "", $converted[1]); 
return round($converted, 3); 
} 

我使用的是USD到INR的轉換器。 調用這個函數

echo convertCurrency(1, "USD", "INR"); 
0

你不能做到這一點的Java代碼原因匯率flatuating每次..你可以當匯率改變使用這個API會自動更新---

<?php 
$from = $_POST["from"]; 
$to = $_POST["to"]; 
$amount = $_POST["amount"]; 
$rawData = currencyConvert($from,$to,$amount); 
$regex = '#\<span class=bld\>(.+?)\<\/span\>#s'; 
preg_match($regex, $rawData, $converted); 
$result = $converted[0]; 
preg_match('!\d+(?:\.\d+)?!', $result, $result); 
echo $result[0]; 

function currencyConvert($from,$to,$amount){ 
    $url = "http://www.google.com/finance/converter?a=$amount&from=$from&to=$to"; 
    $request = curl_init(); 
    $timeOut = 0; 
    curl_setopt ($request, CURLOPT_URL, $url); 
    curl_setopt ($request, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt ($request, CURLOPT_USERAGENT,"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)"); 
    curl_setopt ($request, CURLOPT_CONNECTTIMEOUT, $timeOut); 
    $response = curl_exec($request); 
    curl_close($request); 
    return $response; 
    } 

?>