입력:
10
1.7777777
9.1
출력:
10
1.78
9.1
이 JavaScript 에서 어떻게 합니까?
값이 텍스트 형식:
parseFloat("123.456").toFixed(2);
값이 숫자인 경우:
var numb = 123.23454;
numb = numb.toFixed(2);
그러나 그 같은 값을 1.5 부여하느뇨 1.50" " 있습니다;; 같은 출력입니다. 수정 제안한 @minitech:
var numb = 1.5;
numb = +numb.toFixed(2);
// Note the plus sign that drops any "extra" zeroes at the end.
// It changes the result (which is a string) into a number again (think "0 + foo"),
// which means that it uses only as many digits as necessary.
더 좋은 것 같다 '는' 마스트로런드 솔루션이므로 라운드 제대로 안 된다! 경우에 따라서는 아니다.
Math.round(1.005 * 1000)/1000 // Returns 1 instead of expected 1.01!
예를 들면 다음과 같다:
parseFloat("1.555").toFixed(2); // Returns 1.55 instead of 1.56.
parseFloat("1.5550").toFixed(2); // Returns 1.55 instead of 1.56.
// However, it will return correct result if you round 1.5551.
parseFloat("1.5551").toFixed(2); // Returns 1.56 as expected.
1.3555.toFixed(3) // Returns 1.355 instead of expected 1.356.
// However, it will return correct result if you round 1.35551.
1.35551.toFixed(2); // Returns 1.36 as expected.
내 생각엔 이 같은 일이 실제로 부동 소수점 1.55499994 behind the scenes 1.555 있기 때문이다.
function roundNumber(num, scale) {
if(!("" + num).includes("e")) {
return +(Math.round(num + "e+" + scale) + "e-" + scale);
} else {
var arr = ("" + num).split("e");
var sig = ""
if(+arr[1] + scale > 0) {
sig = "+";
}
return +(Math.round(+arr[0] + "e" + sig + (+arr[1] + scale)) + "e-" + scale);
}
}
https://plnkr.co/edit/uau8BlS1cqbvWPCHJeOy? p = 미리봅니다
사용할 수 있습니다.
function roundToTwo(num) {
return +(Math.round(num + "e+2") + "e-2");
}
이 과정을 매든 에서 찾았다. 그 길을 피할 수 있던 문제가 1.005 [언급한] [2].
roundToTwo(1.005)
1.01
roundToTwo(10)
10
roundToTwo(1.7777777)
1.78
roundToTwo(9.1)
9.1
roundToTwo(1234.5678)
1234.57
[2]: https://stackoverflow.com/questions/11832914/round-up-to-2-decimal-places-in-javascript # comment24719818_11832950
Number.prototype.round = function(places) {
return +(Math.round(this + "e+" + places) + "e-" + places);
}
사용법:
var n = 1.7777;
n.round(2); // 1.78
유닛 테스트:
it.only('should round floats to 2 places', function() {
var cases = [
{ n: 10, e: 10, p:2 },
{ n: 1.7777, e: 1.78, p:2 },
{ n: 1.005, e: 1.01, p:2 },
{ n: 1.005, e: 1, p:0 },
{ n: 1.77777, e: 1.8, p:1 }
]
cases.forEach(function(testCase) {
var r = testCase.n.round(testCase.p);
assert.equal(r, testCase.e, 'didn\'t get right number');
});
})
콩지름에:
Math.round( num * 100 + Number.EPSILON ) / 100
아무도 유의해야 할 것 '누마베리엔실론'.
또한 it& # 39 의 가치가 있는 어떤 사람들은 JavaScript 불확실성 같은 것은 아니다 밝혔다.
여기 따라오렴 '누마베리엔실론'. 그 수가 차이가 존재하는 배정도 부동 소수점 숫자 1 과 다음 번호. That& # 39 에 있다. '1' 과 1 사이의 숫자 '+' 누마베리엔실론 제공합니다. 꾨т 臾몄젣媛?
Math.round( ( num + Number.EPSILON ) * 100 ) / 100
이 질문은 복잡하다. 예를 들어, 함수, 우리는 (숫자) ',' roundTo2DP 부동 소수점 값을 소수점 2 로 처리하는 인수로 및 되돌려줍니다 라운드된. 이러한 각 표현식에서는 평가하십시오 어떻게 해야 합니다.
이번에 '막' 가능성이 있는 것은 있을 수 있고 그 답을 줄 수 있기 때문에 모든 구현될 수 없는 roundTo2DP 같은 3 개의 숫자 명백하네 전달할 수 있다. IEEE 754 이진 부동 소수점 숫자 (JavaScript 를 사용하는 사람이었는가부텀) can& 나타내는 숫자, 즉 모든 3 개의 숫자 리터럴, t # 39 위에 라운드된 확보하십시오 비사양 정수 당근이지를 가장 가까운 유효함 실수. 이 때문에 문제가 발생할 수 있으며, 정확히 , 0.01499999999999999944488848768742172978818416595458984375 이는 0.01 더 가깝게 0.02. 모든 것을 볼 수 있습니다, JavaScript, 또는 다른 브라우저를 콘솔입니다 같은 emc. 세 숫자는 노드입니다 쉘로 통역을 했다고 한다. 그냥 비교해 볼: ,, > < pre> < code>. < b>;;;;;;; /b> < /i> < < i> 0.014999999999999999 = 0.0150000000000000001 true< /code> < /pre>;;;
/**
* Converts num to a decimal string (if it isn't one already) and then rounds it
* to at most dp decimal places.
*
* For explanation of why you'd want to perform rounding operations on a String
* rather than a Number, see http://stackoverflow.com/a/38676273/1709587
*
* @param {(number|string)} num
* @param {number} dp
* @return {string}
*/
function roundStringNumberWithoutTrailingZeroes (num, dp) {
if (arguments.length != 2) throw new Error("2 arguments required");
num = String(num);
if (num.indexOf('e+') != -1) {
// Can't round numbers this large because their string representation
// contains an exponent, like 9.99e+37
throw new Error("num too large");
}
if (num.indexOf('.') == -1) {
// Nothing to do
return num;
}
var parts = num.split('.'),
beforePoint = parts[0],
afterPoint = parts[1],
shouldRoundUp = afterPoint[dp] >= 5,
finalNumber;
afterPoint = afterPoint.slice(0, dp);
if (!shouldRoundUp) {
finalNumber = beforePoint + '.' + afterPoint;
} else if (/^9+$/.test(afterPoint)) {
// If we need to round up a number like 1.9999, increment the integer
// before the decimal point and discard the fractional part.
finalNumber = Number(beforePoint)+1;
} else {
// Starting from the last digit, increment digits until we find one
// that is not 9, then stop
var i = dp-1;
while (true) {
if (afterPoint[i] == '9') {
afterPoint = afterPoint.substr(0, i) +
'0' +
afterPoint.substr(i+1);
i--;
} else {
afterPoint = afterPoint.substr(0, i) +
(Number(afterPoint[i]) + 1) +
afterPoint.substr(i+1);
break;
}
}
finalNumber = beforePoint + '.' + afterPoint;
}
// Remove trailing zeroes from fractional part before returning
return finalNumber.replace(/0+$/, '')
}
사용 예시: ,, > < pre> < code>. ,, i> < b> < 로런드스트린근움베르비투스트라이링제로스 (1.6, 2), /i> < < /b>;;
>. < b>;;;;; < < i> 로런드스트린근움베르비투스트라이링제로스 (10000mb, 2) < /i> /b>;
>. ,, i> < b> < 로런드스트린근움베르비투스트라이링제로스 (0.015, 2), /i> < < /b>;;
>. ,, < b> < i> 로런드스트린근움베르비투스트라이링제로스 (& # 39, 0.015000& # 39, 2), /i> < < /b>;;
>. (1, 1),,, b> < < i> 로런드스트린근움베르비투스트라이링제로스 < /i> < /b>;; 1& # 39, & # 39. >. ,, < b> < i> 로런드스트린근움베르비투스트라이링제로스 (& # 39, 0.015& # 39, 2), /i> < < /b>;;
>. < b>;;;;; < < i> 로런드스트린근움베르비투스트라이링제로스 (0.01499999999999999944488848768742172978818416595458984375, 2) < /i> /b>;
>. ,, < b> < i> 로런드스트린근움베르비투스트라이링제로스 (& # 39, 0.01499999999999999944488848768742172978818416595458984375& # 39, 2), /i> < < /b>;;
이 함수는 아마도 위에 그리웠댔지 피하기 위해 사용할 수 있다는 보고도 판매업체에서 사용자가 입력한 반올림할 번호를 잘못. (이 대안으로 관련 검색어 [round10] (https://github.com/jhohlfeld/round10) 라이브러리 뒤늦게 partnernet 제공하는 기능이 없는 다른 구축상의.) 하지만 와일드링이 두 번째 종류의 수 있습니다 - 값을 연속 확장, 여기서 there& 빼앗아 # 39 의 소수점 표현을 더 많이 생각하고 더 적은 이유가 근사화하는 소수점 더욱 정확한 볼륨과는? 이 경우, 우리는 문자열 t , # 39 don& 매핑하려는 존중하십시오 표현 때문에 표현 (사양 설명에 따라) 는 이미 일종의 라운드된. # 39 라고 보고 싶지 않다, 우리는 don& 할 수 있는 반올림합니다 0.015 " 0. 014999999.375, 014999999.375) 을 0.02 도왔으매 0. 반올림합니다 위해 반올림합니다 0.02". 여기서는 간단히 사용할 수 있는 내장현 ['토피스트'] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed) 메서드입니다. 참고로 '번호 ()' 를 통해 ',' 토피스트 호출하십시오 구체화하십시오 반환되었습니다 얻고 그 번호를 구체화하십시오 나타내줍니다 주님으로부터그에게 트레일링 제로는 (힘입어 문자열이어야 JavaScript 계산하는 방법으로 표현한 번호, 앞서 설명한 이 답).
/**
* Takes a float and rounds it to at most dp decimal places. For example
*
* roundFloatNumberWithoutTrailingZeroes(1.2345, 3)
*
* returns 1.234
*
* Note that since this treats the value passed to it as a floating point
* number, it will have counterintuitive results in some cases. For instance,
*
* roundFloatNumberWithoutTrailingZeroes(0.015, 2)
*
* gives 0.01 where 0.02 might be expected. For an explanation of why, see
* http://stackoverflow.com/a/38676273/1709587. You may want to consider using the
* roundStringNumberWithoutTrailingZeroes function there instead.
*
* @param {number} num
* @param {number} dp
* @return {number}
*/
function roundFloatNumberWithoutTrailingZeroes (num, dp) {
var numToFixedDp = Number(num).toFixed(dp);
return Number(numToFixedDp);
}
정확한 둥글리기 메서드입니다. 출처: Mizilla
(function(){
/**
* Decimal adjustment of a number.
*
* @param {String} type The type of adjustment.
* @param {Number} value The number.
* @param {Integer} exp The exponent (the 10 logarithm of the adjustment base).
* @returns {Number} The adjusted value.
*/
function decimalAdjust(type, value, exp) {
// If the exp is undefined or zero...
if (typeof exp === 'undefined' || +exp === 0) {
return Math[type](value);
}
value = +value;
exp = +exp;
// If the value is not a number or the exp is not an integer...
if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
return NaN;
}
// Shift
value = value.toString().split('e');
value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
// Shift back
value = value.toString().split('e');
return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
}
// Decimal round
if (!Math.round10) {
Math.round10 = function(value, exp) {
return decimalAdjust('round', value, exp);
};
}
// Decimal floor
if (!Math.floor10) {
Math.floor10 = function(value, exp) {
return decimalAdjust('floor', value, exp);
};
}
// Decimal ceil
if (!Math.ceil10) {
Math.ceil10 = function(value, exp) {
return decimalAdjust('ceil', value, exp);
};
}
})();
예를 들면 다음과 같다:
// Round
Math.round10(55.55, -1); // 55.6
Math.round10(55.549, -1); // 55.5
Math.round10(55, 1); // 60
Math.round10(54.9, 1); // 50
Math.round10(-55.55, -1); // -55.5
Math.round10(-55.551, -1); // -55.6
Math.round10(-55, 1); // -50
Math.round10(-55.1, 1); // -60
Math.round10(1.005, -2); // 1.01 -- compare this with Math.round(1.005*100)/100 above
// Floor
Math.floor10(55.59, -1); // 55.5
Math.floor10(59, 1); // 50
Math.floor10(-55.51, -1); // -55.6
Math.floor10(-51, 1); // -60
// Ceil
Math.ceil10(55.51, -1); // 55.6
Math.ceil10(51, 1); // 60
Math.ceil10(-55.59, -1); // -55.5
Math.ceil10(-59, 1); // -50
다음은 간단한 방법은 do it.
Math.round(value * 100) / 100
이를 위한 별도의 기능을 할 수 있습니다 박으래도 저회가 당신꺼에요 표시되어도:
function roundToTwo(value) {
return(Math.round(value * 100) / 100);
}
그런 다음 값 전달 됩니다.
임의의 두 번째 라운드 수를 높일 수 있는 자리로 redhat. 추가하기만 매개변수입니다.
function myRound(value, places) {
var multiplier = Math.pow(10, places);
return (Math.round(value * multiplier) / multiplier);
}
마스트로런드 () 정답 확증하노라 가져다줄래요 않았다. 토피스트 (2) 내가 찾은 더욱 효과적입니다. 아래 예제일 모두:
<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. > 거짓값 -;
console.log(Math.round(43000 / 80000) * 100); // wrong answer
console.log(((43000 / 80000) * 100).toFixed(2)); // correct answer
끝 - < 스니핏 >;!
이 함수 f (x) '번호를 네스토피스트 (2), "'
그렇게 할 수 있는 방법을 몇 가지 방법이 있습니다. 그런 사람들을 위한, 나를 Lodash& # 39 의 변형
function round(number, precision) {
var pair = (number + 'e').split('e')
var value = Math.round(pair[0] + 'e' + (+pair[1] + precision))
pair = (value + 'e').split('e')
return +(pair[0] + 'e' + (+pair[1] - precision))
}
round(0.015, 2) // 0.02
round(1.005, 2) // 1.01
끝 - < 스니핏 >;!
Jquery 는 프로젝트의 경우, 또는 로다시 이벤트수정적절한 '차' 라이브러리보다는 방법을 찾을 수 있습니다.
내가 재거됨 변형 (2) ',' 니컬러스토피스트 때문에 올바르지 않습니다. @Avalanche1 감사합니다.
라바만티스 마르크그 및 솔루션을 제공하는 것보다 훨씬 더 나은 방정식입니다 수락되었습니다. # 39, s, t # 39 don& it& 부끄러워요 그들은 더 많은 업보테스!
다음은 내가 문제를 해결할 수 있는 기능을 사용하여 부동 소수점 자리로 [또한 매든 기반으로] [1]. 일반 (간결하게 않은 것이 아닌 것이 훨씬 더 Lavamantis& # 39 의 솔루션:
function round(value, exp) {
if (typeof exp === 'undefined' || +exp === 0)
return Math.round(value);
value = +value;
exp = +exp;
if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0))
return NaN;
// Shift
value = value.toString().split('e');
value = Math.round(+(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp)));
// Shift back
value = value.toString().split('e');
return +(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp));
}
이 기능을 사용하여:
round(10.8034, 2); // Returns 10.8
round(1.275, 2); // Returns 1.28
round(1.27499, 2); // Returns 1.27
round(1.2345678e+2, 2); // Returns 123.46
round(1234.5678, -2); // Returns 1200
round("123.45"); // Returns 123
[1]: # Example:_Decimal_rounding https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/math/round
<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. > 거짓값 -;
var x = 1.49999999999;
console.log(x.toPrecision(4));
console.log(x.toPrecision(3));
console.log(x.toPrecision(2));
var y = Math.PI;
console.log(y.toPrecision(6));
console.log(y.toPrecision(5));
console.log(y.toPrecision(4));
var z = 222.987654
console.log(z.toPrecision(6));
console.log(z.toPrecision(5));
console.log(z.toPrecision(4));
끝 - < 스니핏 >;!
& # 39 는 그냥 '와' 페르세프로이트 사용되지 않는, 그런 다음 검색하기를 away& # 39;.
<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. > 거짓값 -;
<! - 언어: > js 랭 -;
콘솔드로그 (페르세프로이트 (1.4999) 오토 프레시시온 (3))); 콘솔드로그 (페르세프로이트 (1.005) 오토 프레시시온 (3))); 콘솔드로그 (페르세프로이트 (1.0051) 오토 프레시시온 (3)));
끝 - < 스니핏 >;!