2011-11-28 2 views
1

Number#toFixed()이 일부 숫자에서 제대로 작동하지 않습니다. 예는 : -`toFixed()`가 일부 숫자에서 제대로 작동하지 않습니다.

7.795.toFixed(2) 
//-> 7.79     #Instead it should display 7.80 

8.895.toFixed(2) 
//-> 8.89     #Instead it should display 8.90 

1.105.toFixed(2) 
//-> 1.10     #Instead it should display 1.11 

55.305.toFixed(2) 
//-> 55.30     #Instead it should display 55.31 

이 문제에 대한 해결책으로 저를 제공해 주시기 바랍니다.

+1

'에서는 toFixed()'자바 스크립트 방법 - jQuery를 – ManseUK

답변

1

이것은 jQuery 오류가 아니며, 기본 Javascript의 동작입니다.

해결책은 될 수 있습니다

(Math.round(55.305 * 100)/100) = 55.31 
+0

** (Math.round와는 아무 상관 (9.995 * 100)/100) = 9.99 # 대신에 100을 표시해야합니다. ** –

+0

쉼표 뒤에 숫자를 넣지 않으려면. 'Math.round (9.995)'를 사용하십시오. – Niels

+0

소수점 뒤에 두 개의 숫자가 필요합니다. –

2
function round_float(x,n){ 
    if(!parseInt(n)) 
    var n=0; 
    if(!parseFloat(x)) 
    return false; 
    return Math.round(x*Math.pow(10,n))/Math.pow(10,n); 
} 
round_float(1.105,2).toFixed(2); 

// 결과 : 1.11

관련 문제