开发者

PHP str_replace and or number_format failing

开发者 https://www.devze.com 2023-04-11 13:26 出处:网络
$BRL_PRICE = currency(\"USD\", \"BRL\", $allmoney); echo \"BRL1 = \" . $BRL_PRICE.\"<br />\"; $BRL_PRICE = str_replace(\" \", \"\", $BRL_PRICE);
      $BRL_PRICE = currency("USD", "BRL", $allmoney);
      echo "BRL1 = " . $BRL_PRICE."<br />";
      $BRL_PRICE = str_replace(" ", "", $BRL_PRICE);
      echo "BRL2 = " . $BRL_PRICE."<br />";  
      $BRL_PRICE = number_format($BRL_PRICE, 2);
      echo "BRL3 = " . $BRL_PRICE."<br />";

outputs are..

BRL1 = 1 531.70922
BRL2 = 1 531.70922
BRL3 = 1.00

All I really want is to round up the value to the nearest cents.. 10s place. I know number_format failures because currency() google money converter adds a space instead of a comra or blank.

I want开发者_如何转开发

BRL3 = 1531.71

.

function currency($from_Currency,$to_Currency,$amount) {
    $amount = urlencode($amount);
    $from_Currency = urlencode($from_Currency);
    $to_Currency = urlencode($to_Currency);
    $url = "http://www.google.com/ig/calculator?hl=en&q=$amount$from_Currency=?$to_Currency";
    $ch = curl_init();
    $timeout = 0;
    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch,  CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $rawdata = curl_exec($ch);
    curl_close($ch);
    $data = explode('"', $rawdata);
    $data = explode(' ', $data['3']);
    $var = $data['0'];
    return $var;
}


Don't blame software in cases when you was just too lazy to read documentation:

$BRL_PRICE = number_format($BRL_PRICE, 2, '.', '');

echo number_format(1531.70922, 2, '.', '');


Why not use sprintf('%.2f',$var)


I don't think it is a simple space in your number. Try preg_replace and see what happens:

$BRL_PRICE = preg_replace('/\s+/', '', $BRL_PRICE);


The response you get from google is invalid json. You don't even json_decode it, but just for the log.

str_replace works pretty well (as always), you just need to replace the right string:

$BRL_PRICE = str_replace("\xc2\xa0", "", $BRL_PRICE);

That is the Unicode Character 'NO-BREAK SPACE' (U+00A0).

0

精彩评论

暂无评论...
验证码 换一张
取 消