Javascript : 반올림 된 숫자를 N 소수로 포맷
JavaScript에서 숫자를 소수점 이하 N 자리로 반올림하는 일반적인 방법은 다음과 같습니다.
function roundNumber(num, dec) {
return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
}
function roundNumber(num, dec) {
return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
}
console.log(roundNumber(0.1 + 0.2, 2));
console.log(roundNumber(2.1234, 2));
그러나이 방법은 항상 N 소수점 이하 자릿수로 반올림하는 동안 최대 N 소수점 이하 자릿수로 반올림합니다. 예를 들어 "2.0"은 "2"로 반올림됩니다.
어떤 아이디어?
그것은 반올림 ploblem이 아니라 디스플레이 문제입니다. 숫자는 유효 숫자에 대한 정보를 포함하지 않습니다. 값 2는 2.0000000000000과 같습니다. 반올림 된 값을 문자열로 바꾸면 특정 자릿수를 표시하게됩니다.
다음과 같이 숫자 뒤에 0을 추가 할 수 있습니다.
var s = number.toString();
if (s.indexOf('.') == -1) s += '.';
while (s.length < s.indexOf('.') + 4) s += '0';
(이는 클라이언트의 지역 설정에서 마침표를 소수점 구분 기호로 사용한다고 가정하고 코드가 다른 설정에 대해 작동하려면 더 많은 작업이 필요합니다.)
여기에 주어진 모든 것에 대해 더 간단한 접근법이 있다고 생각하며 Number.toFixed()
이미 JavaScript로 구현 된 방법 입니다.
간단히 작성하십시오.
var myNumber = 2;
myNumber.toFixed(2); //returns "2.00"
myNumber.toFixed(1); //returns "2.0"
기타...
방법을 찾았습니다. 다음은 수정 된 Christoph의 코드입니다.
function toFixed(value, precision) {
var precision = precision || 0,
power = Math.pow(10, precision),
absValue = Math.abs(Math.round(value * power)),
result = (value < 0 ? '-' : '') + String(Math.floor(absValue / power));
if (precision > 0) {
var fraction = String(absValue % power),
padding = new Array(Math.max(precision - fraction.length, 0) + 1).join('0');
result += '.' + padding + fraction;
}
return result;
}
"+ 1"을 추가 한 이유가 궁금하다면 여기 에서 배열 생성자를 사용하여 문자를 반복하는 방법에 대한 자세한 내용을 읽어보십시오 .
일을하는 데 항상 더 나은 방법이 있습니다.
var number = 51.93999999999761;
4 자리 정밀도를 얻고 싶습니다 : 51.94
그냥 해:
number.toPrecision(4);
결과는 51.94입니다.
PHP와 유사한 반올림 방법
아래 코드는 정밀도 매개 변수를 사용하는 고유 한 버전의 Math.round를 고유 한 네임 스페이스에 추가하는 데 사용할 수 있습니다. 위의 예에서 십진수 반올림과 달리 이것은 문자열과의 변환을 수행하지 않으며 정밀도 매개 변수는 PHP 및 Excel과 동일한 방식으로 작동합니다. 따라서 양수 1은 소수점 1 자리로 반올림하고 -1은 10 자리로 반올림합니다.
var myNamespace = {};
myNamespace.round = function(number, precision) {
var factor = Math.pow(10, precision);
var tempNumber = number * factor;
var roundedTempNumber = Math.round(tempNumber);
return roundedTempNumber / factor;
};
myNamespace.round(1234.5678, 1); // 1234.6
myNamespace.round(1234.5678, -1); // 1230
에서 ) (Math.round에 대한 모질라 개발자 참조
제대로 작동하는 코드 (많은 테스트를하지 않음) :
function toFixed(value, precision) {
var precision = precision || 0,
neg = value < 0,
power = Math.pow(10, precision),
value = Math.round(value * power),
integral = String((neg ? Math.ceil : Math.floor)(value / power)),
fraction = String((neg ? -value : value) % power),
padding = new Array(Math.max(precision - fraction.length, 0) + 1).join('0');
return precision ? integral + '.' + padding + fraction : integral;
}
이것은 N 자리로 반올림하는 데 작동합니다 (N 자리로 자르려면 Math.round 호출을 제거하고 Math.trunc 하나를 사용하십시오) :
function roundN(value, digits) {
var tenToN = 10 ** digits;
return /*Math.trunc*/(Math.round(value * tenToN)) / tenToN;
}
Had to resort to such logic at Java in the past when I was authoring data manipulation E-Slate components. That is since I had found out that adding 0.1 many times to 0 you'd end up with some unexpectedly long decimal part (this is due to floating point arithmetics).
A user comment at Format number to always show 2 decimal places calls this technique scaling.
Some mention there are cases that don't round as expected and at http://www.jacklmoore.com/notes/rounding-in-javascript/ this is suggested instead:
function round(value, decimals) {
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}
Here's a link to a Javascript sprintf,
http://www.webtoolkit.info/javascript-sprintf.html
A call to sprintf() is one rounding methodology in perl, but javascript doesn't have that function natively.
http://perldoc.perl.org/functions/sprintf.html
Does that help?
I think below function can help
function roundOff(value,round) {
return (parseInt(value * (10 ** (round + 1))) - parseInt(value * (10 ** round)) * 10) > 4 ? (((parseFloat(parseInt((value + parseFloat(1 / (10 ** round))) * (10 ** round))))) / (10 ** round)) : (parseFloat(parseInt(value * (10 ** round))) / ( 10 ** round));
}
usage : roundOff(600.23458,2);
will return 600.23
If you do not really care about rounding, just added a toFixed(x) and then removing trailing 0es and the dot if necessary. It is not a fast solution.
function format(value, decimals) {
if (value) {
value = value.toFixed(decimals);
} else {
value = "0";
}
if (value.indexOf(".") < 0) { value += "."; }
var dotIdx = value.indexOf(".");
while (value.length - dotIdx <= decimals) { value += "0"; } // add 0's
return value;
}
참고URL : https://stackoverflow.com/questions/2221167/javascript-formatting-a-rounded-number-to-n-decimals
'program tip' 카테고리의 다른 글
AWS S3 : 사용중인 디스크 공간을 확인하려면 어떻게해야합니까? (0) | 2020.08.21 |
---|---|
xcode / storyboard : 막대 버튼을 상단의 도구 모음으로 끌 수 없습니다. (0) | 2020.08.21 |
C / C ++에서 1 비트가 설정되었는지 확인합니다. 즉, int 변수 (0) | 2020.08.21 |
JQuery를 사용하여 그룹의 라디오 버튼이 확인되지 않았는지 확인 (0) | 2020.08.21 |
Notification.Builder를 정확히 사용하는 방법 (0) | 2020.08.21 |