programing tip

JavaScript에서 정확히 두 개의 소수로 숫자 서식 지정

itbloger 2020. 10. 4. 10:39
반응형

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)

당신은 잘못된 답을 얻을 것입니다

자바 스크립트에서 소수점 반올림을 얻는 자연스러운 방법은 없습니다. 자체 폴리 필이 필요하거나 라이브러리를 사용해야합니다. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round에 대한 mozilla의 polyfill을 볼 수 있습니다.


이것은 오래된 주제이지만 여전히 최상위 순위의 Google 결과이며 제공된 솔루션은 동일한 부동 소수점 소수점 문제를 공유합니다. 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"

다양한 예제 및 테스트 ( @ tj-crowder 에게 감사드립니다 !) :

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 솔루션을 사용하여 십진수 길이에 맞게 조정하면 이것이 가장 적합합니다.

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);
}

보고 된 예외에 대해 작동합니다.


이전 답변에 주석을 추가 할 수없는 이유는 모르겠지만 (아마도 눈이 멀었을 수도 있습니다) @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을 반환하지 않는 문제
  • 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을 더하므로 소수점 값 오른쪽에 13 0을 더합니다. 따라서 사용하는 것이 안전해야합니다.

그 후 .toFixed(decimal)항상 올바른 형식으로 숫자를 출력하도록 추가 했습니다 (적절한 양의 소수).

그래서 그것은 거의 다입니다. 잘 사용하세요;)

편집 : 음수의 "수정"기능을 추가했습니다.


소수점 이하 2 자리 숫자를 100 % 확신하는 한 가지 방법 :

(Math.round(num*100)/100).toFixed(2)

이로 인해 반올림 오류가 발생하면 James가 주석에서 설명한대로 다음을 사용할 수 있습니다.

(Math.round((num * 1000)/10)/100).toFixed(2)

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);

이 문제에 대한 정확한 해결책을 찾지 못해서 직접 만들었습니다.

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


@heridev와 저는 jQuery에서 작은 함수를 만들었습니다.

다음을 시도 할 수 있습니다.

HTML

<input type="text" name="one" class="two-digits"><br>
<input type="text" name="two" class="two-digits">​

jQuery

// 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
    });
});

온라인 데모 :

http://jsfiddle.net/c4Wqn/


여기 간단한 것이 있습니다.

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));

Jsfiddle


부동 소수점 값의 문제점은 고정 된 양의 비트로 무한한 양의 (연속적인) 값을 나타내려고한다는 것입니다. 그래서 당연히 플레이에 약간의 손실이있을 것입니다. 그리고 당신은 약간의 가치에 물릴 것입니다.

컴퓨터가 1.275를 부동 소수점 값으로 저장하면 실제로 1.275인지 1.27499999999999993인지, 심지어 1.27500000000000002인지 기억하지 못합니다. 이 값은 소수점 이하 두 자리로 반올림 한 후 다른 결과를 제공해야하지만 컴퓨터의 경우 부동 소수점 값으로 저장 한 후 정확히 동일 하게 보이고 손실 된 데이터를 복원 할 방법이 없기 때문에 그렇지 않습니다 . 추가 계산은 그러한 부정확성을 축적합니다.

따라서 정밀도가 중요하다면 처음부터 부동 소수점 값을 피해야합니다. 가장 간단한 옵션은

  • 용도 헌신적 인 라이브러리를
  • 값을 저장하고 전달하기 위해 문자열 사용 (문자열 연산과 함께)
  • 정수를 사용합니다 (예 : 실제 가치의 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 , 가까운 반올림하는 것이 좋습니다 도에 관계 부동 소수점 연산뿐만 기본 동작. 이러한 수정은 독자를위한 연습으로 남겨집니다. :)


십진수 값을 반올림 한 다음 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


/**
 * MidpointRounding away from zero ('arithmetic' rounding)
 * Uses a half-epsilon for correction. (This offsets IEEE-754
 * half-to-even rounding that was applied at the edge cases).
 */

function RoundCorrect(num, precision = 2) {
	// half epsilon to correct edge cases.
	var c = 0.5 * Number.EPSILON * num;
//	var p = Math.pow(10, precision); //slow
	var p = 1; while (precision--> 0) p *= 10;
	if (num < 0)
		p *= -1;
	return Math.round((num + c) * p) / p;
}

// testing some +ve edge cases
console.log(RoundCorrect(1.005, 2));  // 1.01 correct
console.log(RoundCorrect(2.175, 2));  // 2.18 correct
console.log(RoundCorrect(5.015, 2));  // 5.02 correct

// testing some -ve edge cases
console.log(RoundCorrect(-1.005, 2));  // -1.01 correct
console.log(RoundCorrect(-2.175, 2));  // -2.18 correct
console.log(RoundCorrect(-5.015, 2));  // -5.02 correct


다음은 내 단선 솔루션입니다. Number((yourNumericValueHere).toFixed(2));

다음과 같은 일이 발생합니다.

1) 먼저 .toFixed(2)소수점 자리를 반올림 할 숫자에 적용 합니다. 이것은 값을 숫자에서 문자열로 변환합니다. 따라서 Typescript를 사용하는 경우 다음과 같은 오류가 발생합니다.

" '문자열'유형은 '숫자'유형에 할당 할 수 없습니다."

2) 숫자 값을 반환하거나 문자열을 숫자 값으로 변환하려면 Number()소위 '문자열'값에 함수를 적용하면됩니다 .

자세한 내용은 아래 예를 참조하십시오.

예 : 소수점 이하 5 자리까지의 금액이 있는데 소수점 이하 2 자리까지 줄이려고합니다. 나는 그렇게한다 :

var price = 0.26453;
var priceRounded = Number((price).toFixed(2));
console.log('Original Price: ' + price);
console.log('Price Rounded: ' + priceRounded);


다음 을 전역 범위에 넣으십시오 .

Number.prototype.getDecimals = function ( decDigCount ) {
   return this.toFixed(decDigCount);
}

그리고 다음 시도 :

var a = 56.23232323;
a.getDecimals(2); // will return 56.23

최신 정보

toFixed()사이의 소수의 숫자 만 사용할 수 있습니다 0-20a.getDecimals(25), 자바 스크립트 오류를 생성 할 수 있습니다 그래서 당신은 몇 가지 추가 검사의 예를 추가 할 수 있음을 수용하는

Number.prototype.getDecimals = function ( decDigCount ) {
   return ( decDigCount > 20 ) ? this : this.toFixed(decDigCount);
}

Number(((Math.random() * 100) + 1).toFixed(2))

이것은 소수점 2 자리로 반올림 된 1부터 100까지의 임의의 숫자를 반환합니다.


Number(Math.round(1.005+'e2')+'e-2'); // 1.01

이것은 나를 위해 일했습니다 : JavaScript에서 반올림 소수점


이 응답을 참조로 사용 : 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>


내림

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/1889449https://www.kirupa.com/html5/rounding_numbers_in_javascript.htm 병합 감사합니다.


이 예제를 사용하면 숫자 1.005를 반올림하려고 할 때 여전히 오류가 발생합니다. 해결책은 Math.js와 같은 라이브러리 또는 다음 함수를 사용하는 것입니다.

function round(value: number, decimals: number) {
    return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
}

몇 달 전에이 게시물에서 몇 가지 아이디어를 얻었지만 여기에있는 답변이나 다른 게시물 / 블로그의 답변이 모든 시나리오를 처리 할 수 ​​없습니다 (예 : 테스터가 찾은 음수 및 일부 "행운의 숫자"). 결국 우리 테스터는 아래에서이 방법으로 문제를 찾지 못했습니다. 내 코드 스 니펫 붙여 넣기 :

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)
}

Since toFixed() can only be called on numbers, and unfortunately returns a string, this does all the parsing for you in both directions. You can pass a string or a number, and you get a number back every time! Calling parseNumber(1.49) will give you 1, and parseNumber(1.49,2) will give you 1.50. Just like the best of 'em!


You could also use the .toPrecision() method and some custom code, and always round up to the nth decimal digit regardless the length of int part.

function glbfrmt (number, decimals, seperator) {
    return typeof number !== 'number' ? number : number.toPrecision( number.toString().split(seperator)[0].length + decimals);
}

You could also make it a plugin for a better use.


Simple as this.

var rounded_value=Math.round(value * 100) / 100;

I found a very simple way that solved this problem for me and can be used or adapted:

td[row].innerHTML = price.toPrecision(price.toFixed(decimals).length

100% working!!! Try it

<html>
     <head>
      <script>
      function replacePonto(){
        var input = document.getElementById('qtd');
        var ponto = input.value.split('.').length;
        var slash = input.value.split('-').length;
        if (ponto > 2)
                input.value=input.value.substr(0,(input.value.length)-1);

        if(slash > 2)
                input.value=input.value.substr(0,(input.value.length)-1);

        input.value=input.value.replace(/[^0-9.-]/,'');

        if (ponto ==2)
	input.value=input.value.substr(0,(input.value.indexOf('.')+3));

if(input.value == '.')
	input.value = "";
              }
      </script>
      </head>
      <body>
         <input type="text" id="qtd" maxlength="10" style="width:140px" onkeyup="return replacePonto()">
      </body>
    </html>

참고URL : https://stackoverflow.com/questions/1726630/formatting-a-number-with-exactly-two-decimals-in-javascript

반응형