문제

이 라인의 코드는 라운드를 내 숫자를 진행하고 있습니다.하지만 내가 번호를 얻을 다음과 같다:10.8,2.4,etc.이는 내 생각이 아니다는 두 소수 자릿수의 그래서 어떻게 향상시킬 수 있습니다 다음과 같은?

Math.round(price*Math.pow(10,2))/Math.pow(10,2);

내가 원하는 번호는 다음과 같 10.80,2.40,etc.사용 jQuery 잘 나와 함께.

도움이 되었습니까?

해결책

고정 점 표기법을 사용하여 숫자를 작성하려면 간단히 사용할 수 있습니다. 토픽 방법:

(10.8).toFixed(2); // "10.80"

var num = 2.4;
alert(num.toFixed(2)); // "2.40"

주목하십시오 toFixed() 문자열을 반환합니다.

중요한: Tofixed는 실제로 90%의 둥글지 않으며 둥근 값을 반환하지만 많은 경우 실제로 작동하지 않습니다. 콘솔에서 시도해보십시오.

2.005.toFixed(2)

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

JavaScript에서 소수점 반올림을 얻는 자연스러운 방법은 없으므로 자신의 폴리 필드가 필요하거나 라이브러리를 사용합니다. 이를 위해 Mozilla의 Polyfill을 볼 수 있습니다 https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/math/round

다른 팁

이것은 오래된 주제이지만 여전히 최고 순위의 Google 결과이며 제공되는 솔루션은 동일한 부동 소수점 Decimals 문제를 공유합니다. 다음은 내가 사용하는 (매우 일반적인) 기능입니다. 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);
}

보고 된 예외는 작동합니다.

왜 이전 답변에 댓글을 추가 할 수 없는지 모르겠지만 (어쩌면 나는 희망없이 장님, Dunno) @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);
}

보시다시피 나는 약간의 "수정"을 추가해야했다. " 그것). 이미 패딩 된 숫자에 0.001을 추가하므로 추가됩니다. 10소수점 값의 오른쪽에 s. 따라서 사용하는 것이 안전해야합니다.

그 후 나는 추가했다 .toFixed(decimal) 항상 올바른 형식으로 숫자를 출력하려면 (적절한 양의 소수점).

그래서 그것은 거의입니다. 잘 사용하십시오;)

편집 : 음수의 "수정"에 기능이 추가되었습니다.

100%의 방법은 2 개의 소수판으로 숫자를 얻을 수 있음을 확신합니다.

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

이것이 반올림 오류가 발생하면 James가 그의 의견에서 설명한대로 다음을 사용할 수 있습니다.

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

두 십수 점 후 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.274999999999993, 심지어 1.27500000000000002인지 실제로 기억하지 못합니다. 이 값은 두 명의 소수판으로 반올림 한 후 다른 결과를 제공해야하지만 컴퓨터의 경우 보이지 않기 때문에 그렇지 않습니다. 정확히 동일합니다 부동 소수점 값으로 저장 한 후에는 손실 된 데이터를 복원 할 방법이 없습니다. 추가 계산은 그러한 부정확성 만 축적합니다.

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

  • a 헌신적 인 도서관
  • 값을 저장하고 전달하기 위해 문자열을 사용하십시오 (문자열 연산과 함께)
  • 정수를 사용합니다 (예 : 실제 가치의 백분의 양, 즉 달러 금액 대신 센트의 금액을 전달할 수 있습니다)

예를 들어, 정수를 사용하여 백분의 수를 저장할 때 실제 값을 찾는 기능은 매우 간단합니다.

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

다음은 1 라인 솔루션입니다. 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) JavaScript 오류를 생성 할 수 있으므로 추가 점검을 추가 할 수 있습니다.

Number.prototype.getDecimals = function ( decDigCount ) {
   return ( decDigCount > 20 ) ? this : this.toFixed(decDigCount);
}
Number(((Math.random() * 100) + 1).toFixed(2))

이것은 임의의 숫자를 1 ~ 100 둥근으로 2 진수로 반환합니다.

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/1889449 그리고 https://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));
},

나는 또한 코드 댓글(sorry i forgot 모든 정보는 이미)...나는 전에 응답을 위해 여기에 미래 참고:

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을 제공합니다. 최고의 'EM처럼!

당신은 또한 사용할 수 있습니다 .toPrecision() 방법과 일부 사용자 정의 코드, int 부품의 길이에 관계없이 항상 nth 10 진수 숫자로 반올림합니다.

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

더 잘 사용할 수 있도록 플러그인으로 만들 수도 있습니다.

이렇게 간단합니다.

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

나는이 문제를 해결하고 사용하거나 조정할 수있는 매우 간단한 방법을 찾았습니다.

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

100% 작업 !!! 시도 해봐

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top