2014-07-20 4 views
0

이 함수의 결과는 5.4 ...하지만 5.40이 필요합니다.
간단한 질문이지만이 문제를 해결할 수있는 (깨끗한) 아이디어가 없습니다. 이 문자열을 표시하기위한 것입니다 가정Javascript - 숫자 반올림

은 JS

var test = round(-5.401826873479466,2); 

alert(test+' $'); // = 5.4 $ 

function round(number, decimals) { 
    return Math.round(number * Math.pow(10, decimals))/Math.pow(10, decimals); 
} 

뿐인 http://jsfiddle.net/xMXPz/2/

답변

3

, 당신은 toFixed이 필요합니다

function round(number, decimals) { 
    return number.toFixed(decimals) 
} 

이것은 문자열을 반환합니다. 숫자의 JS 인코딩에서 5.45.40 사이의 차이점은 없습니다. Read more in the MDN.

0

http://ecma-international.org/ecma-262 (이 하나

var test = round(-5.401826873479466,2); 
test=test.toFixed(2); 
alert(test+' $'); 

function round(number, decimals)        { 

return Math.round(number * Math.pow(10, decimals))/Math.pow(10, decimals); 

}

+0

그런 다음 다시, 영업 이익은 언제나 [* Number.prototype.toPrecision *] 사용할 수있는 시도 /5.1/#sec-15.7.4.7). – RobG