2014-07-18 6 views
2

% .2n 형식의 money_format을 사용하고 있지만 이상한 결과가 나타납니다.money_format (샘플 코드 포함)로 예기치 않은 반올림

다른 사람들이 스스로 테스트 할 수 있도록 샘플 코드를 작성했습니다.

<?php 
    setlocale(LC_MONETARY, 'en_US'); 
    $deal = array(
     array(
      'amt' => 1350, 
      'rate' => .75, 
      'lod' => 47 
     ), 
     array(
      'amt' => 990, 
      'rate' => .75, 
      'lod' => 27 
     ), 
     array(
      'amt' => 4180, 
      'rate' => .75, 
      'lod' => 65 
     ), 
     array(
      'amt' => 2370, 
      'rate' => .75, 
      'lod' => 26 
     ) 
    ); 
    foreach ($deal as $value) { 
     $fee = (($value['amt']/1000) * $value['rate']) * $value['lod']; 
     var_dump($fee); 
     echo '<br />money_format: ', money_format('%.2n', $fee), '<br />number_format: ', number_format($fee, 2), '<br /><br />'; 
    } 

출력 :

float(47.5875) 
money_format: $47.59 
number_format: 47.59 

float(20.0475) 
money_format: $20.05 
number_format: 20.05 

float(203.775) 
money_format: $203.77 
number_format: 203.78 

float(46.215) 
money_format: $46.22 
number_format: 46.22 

세 번째 결과를 알 수 있습니다, $ 203.77로 203.775 나타납니다 $ 203.78에 반대.

money_format에 대한 이해가 부족합니다.

phpfiddle 링크 :

<?php 

setlocale(LC_MONETARY, 'en_US'); 

function _money_format($number, $decimals=2){ 
    $number = number_format($number, $decimals); 
    $local_settings = localeconv(); 
    $currency_symbol = $local_settings['currency_symbol']; 
    return $currency_symbol . $number; 
} 

echo _money_format('23.4567'); 

?> 

아직도 당신이 필요 가야로 number_format를 사용하여 + 통화 기호를 받고 : http://phpfiddle.io/fiddle/1909516587

+0

, 그것은 훨씬 더 쉽게 사용. 'money_format'을 사용하는 이유는 무엇입니까? – ssergei

+0

그는 차가워지고 아무도 사용하지 않는 기능을 사용하기를 원합니다. : P – Dharman

+1

이것은 버그 인 것 같습니다. https://bugs.php.net/bug.php?id=61787 – iautomation

답변

1

var_dump 정밀도는 너무 낮게 설정하고 부동 소수점 반올림 값을 표시한다.

ini_set('precision',32); 

또는 $fee로부터 실수 값을 더 표시 할 printf("%01.32f", $fee);을 사용하려고.

예 : 본질 number_format에서 http://ideone.com/2vzXxI

잘못에 (최저 교단을 정밀이 참여하고있다 부동 소수점 연산을 사용하지하려고하고 사용, 일반적으로

echo number_format(23.77499999999997, 2); //returns 23.78 
echo number_format(2.77499999999997, 2); //returns 2.77 

반올림한다 돈 센스 센트), 또는 bcmath 함수에 의존합니다. 플로트와 BC 값

bcscale(4); 
foreach ($deal as $value) { 
    $fee = (float) bcmul(bcmul(bcdiv($value['amt'], 1000), $value['rate']), $value['lod']); 
    echo 'money_format: ' . money_format('%.2n', $fee) . PHP_EOL; 
    echo 'number_format: ' . number_format($fee, 2) . PHP_EOL . PHP_EOL; 
} 

예 : 두 기능의 문제를 해결할 수 bc 수학을 사용하는 계산을 변경 http://php.net/manual/en/book.bc.php

단지`number_format`를 사용하지 왜 http://ideone.com/msbHf0

+0

@Andre BCMath 함수로 수정되었습니다. – fyrye