2012-12-09 3 views
1

아래 코드에서 소수점 이하 두 자리로 반올림하려합니다. 그러나 대부분의 경우 소수점 이하 자릿수를 제어하는 ​​수학 라운드 메서드가 작동하지 않습니다.소수점 이하 자릿수를 제어하는 ​​Math.round()

var newKitAmount = 1; 
    var priceNumber = 168; 
    var updatedTotal = Math.round(priceNumber * newKitAmount*100)/100; 
    alert("total is : " + updatedTotal); //OUTPUTS 168 instead of 168.00 

출력 생성 : 168

원하는 출력 : 168.00

예 2 : 5 * 2 = 10

원하는 출력 : 10.00

JS Fiddle

내가 뭘 잘못하고 있니? 어떻게 해결할 수 있습니까?

+1

(https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/ [당신은'에서는 toFixed()'기능. 보라] Number/toFixed) – Pointy

+0

가능한 복제본 [javascrip에서 float 형식을 지정하는 방법 t?] (@stackoverflow.com/questions/661562/how-to-format-a-float-in-javascript) – GSerg

+0

@GSerg 플로트를 포맷하는 방법에 대해서는 아무것도 묻지 않았다. 중복에 대해 게시하기 전에 질문을 읽으십시오. – AnchovyLegend

답변

8

당신이 당신의 문자열에서 점 자리수의 고정 번호를하려는 경우가 toFixed를 사용한다 : 당신이 때문에 파이어 폭스와 크롬은 반올림하지 사이의 차이 라운드에 함수를 사용해야합니다

var updatedTotal = (priceNumber * newKitAmount).toFixed(2); 
+0

대단히 고마워,이게 내가 필요한거야. – AnchovyLegend

0

에서는 toFixed와 같은 방법으로 ...

function toFixed(a,b){ //where a is the number and b is the number of decimals 
    var m = Math.pow(10,b); 
    return Math.round(parseFloat(a)*m)/m; 
} 
관련 문제