JavaScript에서 소수점 두 개로 숫자 형식 지정
소수점 이하 두 자리까지 반올림하는 코드 줄이 있어요하지만 10.8, 2.4 등의 숫자가 나옵니다.소수점 두 자리라는 내 생각이 아닌데, 어떻게 하면 다음을 개선할 수 있을까요?
Math.round(price*Math.pow(10,2))/Math.pow(10,2);
10.80, 2.40 등의 숫자를 원합니다.저는 jQuery를 사용해도 괜찮습니다.
고정 소수점 표기법을 사용하여 숫자의 형식을 지정하려면 toFixed 메서드를 사용합니다.
(10.8).toFixed(2); // "10.80"
var num = 2.4;
alert(num.toFixed(2)); // "2.40"
:toFixed()문자열을 반환합니다.
중요: toFixed는 90% 반올림되지 않으며 반올림된 값을 반환하지만 대부분의 경우 작동하지 않습니다.
예:
2.005.toFixed(2) === "2.00"
갱신:
요즘은 컨스트럭터를 사용할 수 있습니다.ECMAScript Internationalization API Specification(ECMA402)의 일부입니다.IE11을 포함하여 브라우저가 상당히 잘 지원되며 Node.js에서도 완전히 지원됩니다.
const formatter = new Intl.NumberFormat('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
console.log(formatter.format(2.005)); // "2.01"
console.log(formatter.format(1.345)); // "1.35"
'하다'를 도 있습니다.toLocaleString으로는 method를 합니다.Intl API:
const format = (num, decimals) => num.toLocaleString('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
console.log(format(2.005)); // "2.01"
console.log(format(1.345)); // "1.35"
또한 이 API는 천 개의 구분 기호, 통화 기호 등 다양한 형식 옵션을 제공합니다.
이것은 오래된 토픽이지만 여전히 구글의 최고 순위 결과와 제공된 솔루션은 동일한 부동 소수점 소수점 문제를 공유합니다.MDN 덕분에 사용하는 (매우 일반적인) 기능은 다음과 같습니다.
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(1.275, 2); // Returns 1.28
round(1.27499, 2); // Returns 1.27
이 범용성은 다음과 같은 뛰어난 기능을 제공합니다.
round(1234.5678, -2); // Returns 1200
round(1.2345678e+2, 2); // Returns 123.46
round("123.45"); // Returns 123
OP의 질문에 답하려면 다음과 같이 입력해야 합니다.
round(10.8034, 2).toFixed(2); // Returns "10.80"
round(10.8, 2).toFixed(2); // Returns "10.80"
또는 보다 간결하고 일반적이지 않은 함수의 경우:
function round2Fixed(value) {
value = +value;
if (isNaN(value))
return NaN;
// Shift
value = value.toString().split('e');
value = Math.round(+(value[0] + 'e' + (value[1] ? (+value[1] + 2) : 2)));
// Shift back
value = value.toString().split('e');
return (+(value[0] + 'e' + (value[1] ? (+value[1] - 2) : -2))).toFixed(2);
}
다음 연락처로 문의처:
round2Fixed(10.8034); // Returns "10.80"
round2Fixed(10.8); // Returns "10.80"
다양한 예시와 테스트(@티제이 크라우더!덕분에):
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));
}
function naive(value, exp) {
if (!exp) {
return Math.round(value);
}
var pow = Math.pow(10, exp);
return Math.round(value * pow) / pow;
}
function test(val, places) {
subtest(val, places);
val = typeof val === "string" ? "-" + val : -val;
subtest(val, places);
}
function subtest(val, places) {
var placesOrZero = places || 0;
var naiveResult = naive(val, places);
var roundResult = round(val, places);
if (placesOrZero >= 0) {
naiveResult = naiveResult.toFixed(placesOrZero);
roundResult = roundResult.toFixed(placesOrZero);
} else {
naiveResult = naiveResult.toString();
roundResult = roundResult.toString();
}
$("<tr>")
.append($("<td>").text(JSON.stringify(val)))
.append($("<td>").text(placesOrZero))
.append($("<td>").text(naiveResult))
.append($("<td>").text(roundResult))
.appendTo("#results");
}
test(0.565, 2);
test(0.575, 2);
test(0.585, 2);
test(1.275, 2);
test(1.27499, 2);
test(1234.5678, -2);
test(1.2345678e+2, 2);
test("123.45");
test(10.8034, 2);
test(10.8, 2);
test(1.005, 2);
test(1.0005, 2);
table {
border-collapse: collapse;
}
table, td, th {
border: 1px solid #ddd;
}
td, th {
padding: 4px;
}
th {
font-weight: normal;
font-family: sans-serif;
}
td {
font-family: monospace;
}
<table>
<thead>
<tr>
<th>Input</th>
<th>Places</th>
<th>Naive</th>
<th>Thorough</th>
</tr>
</thead>
<tbody id="results">
</tbody>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
저는 보통 이것을 개인 라이브러리에 추가하고 몇 가지 제안을 한 후 @TIMINeutron 솔루션을 사용하여 10진수 길이에 적합하게 만듭니다.
function precise_round(num, decimals) {
var t = Math.pow(10, decimals);
return (Math.round((num * t) + (decimals>0?1:0)*(Math.sign(num) * (10 / Math.pow(100, decimals)))) / t).toFixed(decimals);
}
는 보고된 예외에 대해 작동합니다.
소수점 2개가 있는 숫자를 100% 확인하는 한 가지 방법은 다음과 같습니다.
(Math.round(num*100)/100).toFixed(2)
이로 인해 반올림 오류가 발생할 경우 James가 설명했듯이 다음을 사용할 수 있습니다.
(Math.round((num * 1000)/10)/100).toFixed(2)
왜 이전 답변에 코멘트를 추가할 수 없는지는 모르겠지만(아마 눈이 멀어서 잘 모르겠지만), 저는 @Miguel의 답변을 사용하여 해결책을 생각해냈습니다.
function precise_round(num,decimals) {
return Math.round(num*Math.pow(10, decimals)) / Math.pow(10, decimals);
}
그리고 두 가지 코멘트(@bighostkim과 @Imre에서):
- 제에
precise_round(1.275,2)1.28 반환 1.28 - 제에
precise_round(6,2)6.00으로 하다
최종 해결책은 다음과 같습니다.
function precise_round(num,decimals) {
var sign = num >= 0 ? 1 : -1;
return (Math.round((num*Math.pow(10,decimals)) + (sign*0.001)) / Math.pow(10,decimals)).toFixed(decimals);
}
보다시피 저는 약간의 "수정"을 추가해야 했습니다(그것은 그것이 아닙니다만, Math.round는 손실이 있기 때문에 - jsfiddle.net에서 확인할 수 있습니다 - 이것이 제가 "수정"하는 방법을 아는 유일한 방법입니다).숫자에되어 0.001이 .따라서 이 번호는1 개010시 10분그래서 그것은 사용하기에 안전할 것이다.
에 저는 '아까보다'를 넣었습니다..toFixed(decimal)올바른 형식(올바른 소수점 포함)으로 항상 숫자를 출력합니다.
그래서 거의 다 됐습니다.잘 사용하세요;)
EDIT: 음수의 "수정"에 기능이 추가되었습니다.
toFixed(n)는 소수점 뒤에 n개의 길이를 제공하며, toPrecision(x)은 x개의 총 길이를 제공합니다.
아래의 방법을 사용하세요.
// Example: toPrecision(4) when the number has 7 digits (3 before, 4 after)
// It will round to the tenths place
num = 500.2349;
result = num.toPrecision(4); // result will equal 500.2
그리고 번호를 고정하고 싶다면
result = num.toFixed(2);
빠르고 간단하게
parseFloat(number.toFixed(2))
예
let number = 2.55435930
let roundedString = number.toFixed(2) // "2.55"
let twoDecimalsNumber = parseFloat(roundedString) // 2.55
let directly = parseFloat(number.toFixed(2)) // 2.55
이 문제에 대한 정확한 해결책을 찾지 못했기 때문에 자체 솔루션을 만들었습니다.
function inprecise_round(value, decPlaces) {
return Math.round(value*Math.pow(10,decPlaces))/Math.pow(10,decPlaces);
}
function precise_round(value, decPlaces){
var val = value * Math.pow(10, decPlaces);
var fraction = (Math.round((val-parseInt(val))*10)/10);
//this line is for consistency with .NET Decimal.Round behavior
// -342.055 => -342.06
if(fraction == -0.5) fraction = -0.6;
val = Math.round(parseInt(val) + fraction) / Math.pow(10, decPlaces);
return val;
}
예:
function inprecise_round(value, decPlaces) {
return Math.round(value * Math.pow(10, decPlaces)) / Math.pow(10, decPlaces);
}
function precise_round(value, decPlaces) {
var val = value * Math.pow(10, decPlaces);
var fraction = (Math.round((val - parseInt(val)) * 10) / 10);
//this line is for consistency with .NET Decimal.Round behavior
// -342.055 => -342.06
if (fraction == -0.5) fraction = -0.6;
val = Math.round(parseInt(val) + fraction) / Math.pow(10, decPlaces);
return val;
}
// This may produce different results depending on the browser environment
console.log("342.055.toFixed(2) :", 342.055.toFixed(2)); // 342.06 on Chrome & IE10
console.log("inprecise_round(342.055, 2):", inprecise_round(342.055, 2)); // 342.05
console.log("precise_round(342.055, 2) :", precise_round(342.055, 2)); // 342.06
console.log("precise_round(-342.055, 2) :", precise_round(-342.055, 2)); // -342.06
console.log("inprecise_round(0.565, 2) :", inprecise_round(0.565, 2)); // 0.56
console.log("precise_round(0.565, 2) :", precise_round(0.565, 2)); // 0.57
여기 간단한 것이 있습니다.
function roundFloat(num,dec){
var d = 1;
for (var i=0; i<dec; i++){
d += "0";
}
return Math.round(num * d) / d;
}
★★★와 같이 alert(roundFloat(1.79209243929,4));
반올림
function round_down(value, decPlaces) {
return Math.floor(value * Math.pow(10, decPlaces)) / Math.pow(10, decPlaces);
}
반올림
function round_up(value, decPlaces) {
return Math.ceil(value * Math.pow(10, decPlaces)) / Math.pow(10, decPlaces);
}
가장 가까운 라운드
function round_nearest(value, decPlaces) {
return Math.round(value * Math.pow(10, decPlaces)) / Math.pow(10, decPlaces);
}
https://stackoverflow.com/a/7641824/1889449 와 https://www.kirupa.com/html5/rounding_numbers_in_javascript.htm 를 통합했습니다.감사합니다.
@heridev와 저는 jQuery에서 작은 함수를 만들었습니다.
다음을 시도할 수 있습니다.
HTML
<input type="text" name="one" class="two-digits"><br>
<input type="text" name="two" class="two-digits">
j쿼리
// apply the two-digits behaviour to elements with 'two-digits' as their class
$( function() {
$('.two-digits').keyup(function(){
if($(this).val().indexOf('.')!=-1){
if($(this).val().split(".")[1].length > 2){
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixed(2);
}
}
return this; //for chaining
});
});
데모 온라인:
부동소수점 값의 문제는 부동소수점 값이 고정 비트 수로 무한대의 (연속적인) 값을 나타내려고 한다는 것입니다.그러니 당연히, 어떤 손실도 있을 것이고, 당신은 어떤 가치관에 물리게 될 것입니다.
컴퓨터가 부동소수점 값으로 1.275를 저장하면 1.275인지 1.274999999999993인지 1.27500000000000002인지도 실제로 기억되지 않습니다.이러한 값은 소수점 2개로 반올림한 후에 다른 결과를 얻을 수 있지만 그렇지 않습니다.컴퓨터의 경우 부동소수점 값으로 저장한 후에는 완전히 동일하고 손실된 데이터를 복원할 방법이 없기 때문입니다.더 이상의 계산은 그러한 부정확성을 축적할 뿐이다.
따라서 정밀도가 중요한 경우 처음부터 부동 소수점 값을 사용하지 않도록 해야 합니다.가장 간단한 방법은
- 전용 도서관을 이용하다
- 값 저장 및 전달에 문자열 사용(문자열 연산으로 연결됨)
- 정수 사용(예: 실제 값의 100분의 1을 전달할 수 있음)
예를 들어 정수를 사용하여 100분의 1의 수를 저장하는 경우 실제 값을 찾는 함수는 매우 간단합니다.
function descale(num, decimals) {
var hasMinus = num < 0;
var numString = Math.abs(num).toString();
var precedingZeroes = '';
for (var i = numString.length; i <= decimals; i++) {
precedingZeroes += '0';
}
numString = precedingZeroes + numString;
return (hasMinus ? '-' : '')
+ numString.substr(0, numString.length-decimals)
+ '.'
+ numString.substr(numString.length-decimals);
}
alert(descale(127, 2));
문자열을 사용하면 반올림이 필요하지만 여전히 관리할 수 있습니다.
function precise_round(num, decimals) {
var parts = num.split('.');
var hasMinus = parts.length > 0 && parts[0].length > 0 && parts[0].charAt(0) == '-';
var integralPart = parts.length == 0 ? '0' : (hasMinus ? parts[0].substr(1) : parts[0]);
var decimalPart = parts.length > 1 ? parts[1] : '';
if (decimalPart.length > decimals) {
var roundOffNumber = decimalPart.charAt(decimals);
decimalPart = decimalPart.substr(0, decimals);
if ('56789'.indexOf(roundOffNumber) > -1) {
var numbers = integralPart + decimalPart;
var i = numbers.length;
var trailingZeroes = '';
var justOneAndTrailingZeroes = true;
do {
i--;
var roundedNumber = '1234567890'.charAt(parseInt(numbers.charAt(i)));
if (roundedNumber === '0') {
trailingZeroes += '0';
} else {
numbers = numbers.substr(0, i) + roundedNumber + trailingZeroes;
justOneAndTrailingZeroes = false;
break;
}
} while (i > 0);
if (justOneAndTrailingZeroes) {
numbers = '1' + trailingZeroes;
}
integralPart = numbers.substr(0, numbers.length - decimals);
decimalPart = numbers.substr(numbers.length - decimals);
}
} else {
for (var i = decimalPart.length; i < decimals; i++) {
decimalPart += '0';
}
}
return (hasMinus ? '-' : '') + integralPart + (decimals > 0 ? '.' + decimalPart : '');
}
alert(precise_round('1.275', 2));
alert(precise_round('1.27499999999999993', 2));
이 함수는 0에서 가장 가까운 값으로 반올림하고 IEEE 754에서는 가장 가까운 값으로 반올림하여 부동소수점 연산의 기본 동작으로 사용할 것을 권장합니다.이러한 수정은 독자의 연습으로 남습니다.
크리스찬 C 위에 건물을 짓고 있어 Salvado의 답변은 다음과 같습니다.Number타이핑하고, 반올림도 잘 하고 있는 것 같습니다.
const roundNumberToTwoDecimalPlaces = (num) => Number(new Intl.NumberFormat('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
}).format(num));
roundNumberToTwoDecimalPlaces(1.344); // => 1.34
roundNumberToTwoDecimalPlaces(1.345); // => 1.35
점이 이 은 필요 입니다..format()이 되어 때, 그리고 체인이 Number라고 입력합니다
이하를 반올림한 , '소수점 이하'를 사용합니다.toFixed(x)를 참조해 주세요.
function parseDecimalRoundAndFixed(num,dec){
var d = Math.pow(10,dec);
return (Math.round(num * d) / d).toFixed(dec);
}
불러
parseDecimalRoundAndFixed(10.800243929,4) => 10.80 parseDecimalRoundAndFixed(10.807243929,2) => 10.81
Number(Math.round(1.005+'e2')+'e-2'); // 1.01
이것은 나에게 효과가 있었다: JavaScript에서 소수점 반올림
이 예에서는 1.005를 반올림하려고 해도 오류가 발생합니다.해결 방법은 Math.js와 같은 라이브러리 또는 이 함수를 사용하는 것입니다.
function round(value: number, decimals: number) {
return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
}
한 줄의 솔루션을 다음에 제시하겠습니다.
다음과 같이 처리됩니다.
1) ㄹ 수 있다를 ..toFixed(2)소수점 이하를 반올림할 수 있습니다.그러면 값이 숫자에서 문자열로 변환됩니다. 타이프스크립트를, 타이프스크립트는 같은 하게 됩니다.
"'string' 유형은 'number' 유형에 할당할 수 없습니다.
2)을 숫자로 하려면 2) 숫자 값을.Number()이른바 '문자열' 값으로 기능합니다.
상세한 것에 대하여는, 다음의 예를 참조해 주세요.
예: 소수점 이하 5자리까지 사용할 수 있는 금액이 있는데 소수점 이하 2자리까지 줄이고 싶습니다.나는 이렇게 한다:
var price = 0.26453;
var priceRounded = Number((price).toFixed(2));
console.log('Original Price: ' + price);
console.log('Price Rounded: ' + priceRounded);
스케일링으로 .round(num * p) / p
간단한 구현
중간값과 함께 다음 함수를 사용하면 예상대로 반올림된 상한 값 또는 입력에 따라 반올림된 하한 값을 얻을 수 있습니다.
★★★★★★★★★★★★★★★★★.inconsistency반올림 시 클라이언트 코드의 버그를 검출하기 어려운 경우가 있습니다.
function naiveRound(num, decimalPlaces) {
var p = Math.pow(10, decimalPlaces);
return Math.round(num * p) / p;
}
console.log( naiveRound(1.245, 2) ); // 1.25 correct (rounded as expected)
console.log( naiveRound(1.255, 2) ); // 1.25 incorrect (should be 1.26)
구현의 향상
이 수를 지수 표기 문자열로 변환하면 양의 숫자는 예상대로 반올림됩니다.단, 음수는 양수와 다르게 반올림한다는 점에 유의하시기 바랍니다.
실제로 기본적으로 "반올림"과 동등한 기능을 수행합니다.round(-1.005, 2)-1round(1.005, 2)1.01. lodash _.round 메서드는 이 기술을 사용합니다.
/**
* Round half up ('round half towards positive infinity')
* Uses exponential notation to avoid floating-point issues.
* Negative numbers round differently than positive numbers.
*/
function round(num, decimalPlaces) {
num = Math.round(num + "e" + decimalPlaces);
return Number(num + "e" + -decimalPlaces);
}
// test rounding of half
console.log( round(0.5, 0) ); // 1
console.log( round(-0.5, 0) ); // 0
// testing edge cases
console.log( round(1.005, 2) ); // 1.01
console.log( round(2.175, 2) ); // 2.18
console.log( round(5.015, 2) ); // 5.02
console.log( round(-1.005, 2) ); // -1
console.log( round(-2.175, 2) ); // -2.17
console.log( round(-5.015, 2) ); // -5.01
음수를 반올림할 때 일반적인 동작을 원할 경우 Math.round()를 호출하기 전에 음수를 양수로 변환한 다음 반환하기 전에 음수로 다시 변환해야 합니다.
// Round half away from zero
function round(num, decimalPlaces) {
num = Math.round(Math.abs(num) + "e" + decimalPlaces) * Math.sign(num);
return Number(num + "e" + -decimalPlaces);
}
반올림 함수를 호출하기 전에 엡실론 보정이 적용되는 라운드 투 근접('0에서 반올림 반' 사용)을 수행하는 다른 순수 수학 기법이 있습니다.
반올림 전 수에 가능한 최소 부동값(= 1.0 ulp, 꼴찌 단위)을 더하면 됩니다.이 값은 숫자 뒤에 0이 아닌 다음 표시 가능한 값으로 이동합니다.
/**
* Round half away from zero ('commercial' rounding)
* Uses correction to offset floating-point inaccuracies.
* Works symmetrically for positive and negative numbers.
*/
function round(num, decimalPlaces) {
var p = Math.pow(10, decimalPlaces);
var e = Number.EPSILON * num * p;
return Math.round((num * p) + e) / p;
}
// test rounding of half
console.log( round(0.5, 0) ); // 1
console.log( round(-0.5, 0) ); // -1
// testing edge cases
console.log( round(1.005, 2) ); // 1.01
console.log( round(2.175, 2) ); // 2.18
console.log( round(5.015, 2) ); // 5.02
console.log( round(-1.005, 2) ); // -1.01
console.log( round(-2.175, 2) ); // -2.18
console.log( round(-5.015, 2) ); // -5.02
이는 특히 1.005, 2.675 및 16.235와 같이 마지막 소수점 위치에 "5"가 있는 10진수 부호화 중에 발생할 수 있는 암묵적인 반올림 오류를 상쇄하기 위해 필요합니다.정말로.1.005으로 10진법으로 1.0049999999999999 플로트, 64비트 바이너리 플로트,1234567.005으로 10진법으로 1234567.004999999888241364번
바이너리수 「」는 가 있습니다.round-off error는 (1)와 (2) 머신 엡실론(2^-52)의 크기에 따라 .
다음 항목을 글로벌 범위에 넣습니다.
Number.prototype.getDecimals = function ( decDigCount ) {
return this.toFixed(decDigCount);
}
그 후 다음을 시도합니다.
var a = 56.23232323;
a.getDecimals(2); // will return 56.23
갱신하다
:toFixed() 할 수 0-20 ㅇㅇㅇ.a.getDecimals(25)오류가 할 수 체크: script 오오 i i i i i i i i)를 추가할 수 .
Number.prototype.getDecimals = function ( decDigCount ) {
return ( decDigCount > 20 ) ? this : this.toFixed(decDigCount);
}
Number(((Math.random() * 100) + 1).toFixed(2))
1에서 100까지의 임의의 숫자를 소수점 이하 2자리 반올림합니다.
이 응답을 참조로 사용:https://stackoverflow.com/a/21029698/454827
동적 소수점 수를 구하는 함수를 만듭니다.
function toDec(num, dec)
{
if(typeof dec=='undefined' || dec<0)
dec = 2;
var tmp = dec + 1;
for(var i=1; i<=tmp; i++)
num = num * 10;
num = num / 10;
num = Math.round(num);
for(var i=1; i<=dec; i++)
num = num / 10;
num = num.toFixed(dec);
return num;
}
여기서의 작업 예:https://jsfiddle.net/wpxLduLc/
parse = function (data) {
data = Math.round(data*Math.pow(10,2))/Math.pow(10,2);
if (data != null) {
var lastone = data.toString().split('').pop();
if (lastone != '.') {
data = parseFloat(data);
}
}
return data;
};
$('#result').html(parse(200)); // output 200
$('#result1').html(parse(200.1)); // output 200.1
$('#result2').html(parse(200.10)); // output 200.1
$('#result3').html(parse(200.109)); // output 200.11
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="result"></div>
<div id="result1"></div>
<div id="result2"></div>
<div id="result3"></div>
몇 달 전에 이 게시물에서 아이디어를 얻었지만, 여기에서는 답변이 하나도 없고, 다른 게시물/블로그의 답변도 모든 시나리오를 처리할 수 없습니다(예: 음수 및 테스터가 발견한 "행운의 숫자").결국, 우리의 테스터는 아래의 이 방법에서 어떠한 문제도 발견하지 못했습니다.코드 조각 붙여넣기:
fixPrecision: function (value) {
var me = this,
nan = isNaN(value),
precision = me.decimalPrecision;
if (nan || !value) {
return nan ? '' : value;
} else if (!me.allowDecimals || precision <= 0) {
precision = 0;
}
//[1]
//return parseFloat(Ext.Number.toFixed(parseFloat(value), precision));
precision = precision || 0;
var negMultiplier = value < 0 ? -1 : 1;
//[2]
var numWithExp = parseFloat(value + "e" + precision);
var roundedNum = parseFloat(Math.round(Math.abs(numWithExp)) + 'e-' + precision) * negMultiplier;
return parseFloat(roundedNum.toFixed(precision));
},
코드 코멘트도 있습니다(세부사항을 모두 잊어버려서 죄송합니다)향후 참조를 위해 여기에 답변을 게시합니다.
9.995 * 100 = 999.4999999999999
Whereas 9.995e2 = 999.5
This discrepancy causes Math.round(9.995 * 100) = 999 instead of 1000.
Use e notation instead of multiplying /dividing by Math.Pow(10,precision).
수식어를 수정했습니다.소수점 2만을 지원합니다.
$(function(){
//input number only.
convertNumberFloatZero(22); // output : 22.00
convertNumberFloatZero(22.5); // output : 22.50
convertNumberFloatZero(22.55); // output : 22.55
convertNumberFloatZero(22.556); // output : 22.56
convertNumberFloatZero(22.555); // output : 22.55
convertNumberFloatZero(22.5541); // output : 22.54
convertNumberFloatZero(22222.5541); // output : 22,222.54
function convertNumberFloatZero(number){
if(!$.isNumeric(number)){
return 'NaN';
}
var numberFloat = number.toFixed(3);
var splitNumber = numberFloat.split(".");
var cNumberFloat = number.toFixed(2);
var cNsplitNumber = cNumberFloat.split(".");
var lastChar = splitNumber[1].substr(splitNumber[1].length - 1);
if(lastChar > 0 && lastChar < 5){
cNsplitNumber[1]--;
}
return Number(splitNumber[0]).toLocaleString('en').concat('.').concat(cNsplitNumber[1]);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
(Math.round((10.2)*100)/100).toFixed(2)
그 결과, 다음과 같이 됩니다.10.20
(Math.round((.05)*100)/100).toFixed(2)
그 결과, 다음과 같이 됩니다.0.05
(Math.round((4.04)*100)/100).toFixed(2)
그 결과, 다음과 같이 됩니다.4.04
기타.
/*Due to all told stuff. You may do 2 things for different purposes:
When showing/printing stuff use this in your alert/innerHtml= contents:
YourRebelNumber.toFixed(2)*/
var aNumber=9242.16;
var YourRebelNumber=aNumber-9000;
alert(YourRebelNumber);
alert(YourRebelNumber.toFixed(2));
/*and when comparing use:
Number(YourRebelNumber.toFixed(2))*/
if(YourRebelNumber==242.16)alert("Not Rounded");
if(Number(YourRebelNumber.toFixed(2))==242.16)alert("Rounded");
/*Number will behave as you want in that moment. After that, it'll return to its defiance.
*/
이것은 매우 심플하고, 다른 것들과 마찬가지로 기능합니다.
function parseNumber(val, decimalPlaces) {
if (decimalPlaces == null) decimalPlaces = 0
var ret = Number(val).toFixed(decimalPlaces)
return Number(ret)
}
toFixed()는 숫자에 대해서만 호출할 수 있으며 안타깝게도 문자열을 반환하기 때문에 양방향으로 모든 해석을 수행합니다.문자열이나 번호를 건네주면 매번 번호를 돌려받을 수 있어요!parseNumber(1.49)를 호출하면 1이 되고 parseNumber(1.49,2)를 호출하면 1.50이 됩니다.그들 중 최고처럼!
,도할 수 ..toPrecision()메서드와 일부 커스텀 코드를 지정합니다.int 부분의 길이에 관계없이 항상 소수점 이하 n자리까지 반올림합니다.
function glbfrmt (number, decimals, seperator) {
return typeof number !== 'number' ? number : number.toPrecision( number.toString().split(seperator)[0].length + decimals);
}
더 나은 사용을 위해 플러그인으로 만들 수도 있습니다.
다음은 https://stackoverflow.com/a/21323330/916734의 TypeScript 구현입니다.또, 기능을 탑재해, 옵션의 디지트 오프셋도 할 수 있습니다.
export function round(rawValue: number | string, precision = 0, fractionDigitOffset = 0): number | string {
const value = Number(rawValue);
if (isNaN(value)) return rawValue;
precision = Number(precision);
if (precision % 1 !== 0) return NaN;
let [ stringValue, exponent ] = scientificNotationToParts(value);
let shiftExponent = exponentForPrecision(exponent, precision, Shift.Right);
const enlargedValue = toScientificNotation(stringValue, shiftExponent);
const roundedValue = Math.round(enlargedValue);
[ stringValue, exponent ] = scientificNotationToParts(roundedValue);
const precisionWithOffset = precision + fractionDigitOffset;
shiftExponent = exponentForPrecision(exponent, precisionWithOffset, Shift.Left);
return toScientificNotation(stringValue, shiftExponent);
}
enum Shift {
Left = -1,
Right = 1,
}
function scientificNotationToParts(value: number): Array<string> {
const [ stringValue, exponent ] = value.toString().split('e');
return [ stringValue, exponent ];
}
function exponentForPrecision(exponent: string, precision: number, shift: Shift): number {
precision = shift * precision;
return exponent ? (Number(exponent) + precision) : precision;
}
function toScientificNotation(value: string, exponent: number): number {
return Number(`${value}e${exponent}`);
}
저는 이 문제를 해결하고 사용 또는 적응할 수 있는 매우 간단한 방법을 찾았습니다.
td[row].innerHTML = price.toPrecision(price.toFixed(decimals).length
언급URL : https://stackoverflow.com/questions/1726630/formatting-a-number-with-exactly-two-decimals-in-javascript
'source' 카테고리의 다른 글
| DEFAULT 절에 CURRENT_TIMESTamp가 있는 TIMESTAMP 열은 왜1개밖에 없어요? (0) | 2022.10.26 |
|---|---|
| 블레이드 템플릿 뷰를 원시 HTML 문자열로 가져오는 방법 (0) | 2022.10.26 |
| 클래스 경로의 Java 패키지에서 모든 클래스를 읽으려면 어떻게 해야 합니까? (0) | 2022.10.26 |
| 각도 간에 데이터 공유JS 컨트롤러 (0) | 2022.10.26 |
| '{"syslog":[],"received":[],"syslog":[]'는 유효한 쿼리가 아닙니다. (0) | 2022.10.26 |