Formatowanie liczby z dokładnie dwoma po przecinku w JavaScript

Mam ten wiersz kodu, który zaokrągla moje liczby do dwóch miejsc po przecinku. Ale dostaję takie liczby: 10,8, 2,4 itd. To nie jest mój pomysł na dwa miejsca po przecinku, więc jak mogę poprawić następujące?

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

Chcę liczby takie jak 10.80, 2.40 itp. Używanie jQuery mi nie przeszkadza.

Author: Peter Mortensen, 2009-11-13

28 answers

Aby sformatować liczbę za pomocą notacji punktowej, możesz po prostu użyć metody toFixed :

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

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

Zauważ, że toFixed() zwraca łańcuch znaków.

IMPORTANT: zauważ, że toFixed w rzeczywistości nie zaokrągla, w 90% przypadków zwróci zaokrągloną wartość, ale w wielu przypadkach nie działa. Spróbuj tego w konsoli:

2.005.toFixed(2)

Dostaniesz złą odpowiedź

Nie ma naturalnego sposobu na uzyskanie zaokrąglenia dziesiętnego w javascript, ty będzie potrzebował własnego polyfill lub skorzystać z biblioteki. Możesz spojrzeć na polyfill Mozilli dla tego https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round

 906
Author: CMS,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-16 18:16:05

To stary temat, ale wciąż najwyżej oceniane wyniki Google i oferowane rozwiązania mają tę samą kwestię dziesiętną zmiennoprzecinkową. Oto (bardzo ogólna) funkcja, której używam, dzięki 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));
}

Jak widać, nie dostajemy tych problemów:

round(1.275, 2);   // Returns 1.28
round(1.27499, 2); // Returns 1.27

Ta generyczność zapewnia również kilka fajnych rzeczy:

round(1234.5678, -2);   // Returns 1200
round(1.2345678e+2, 2); // Returns 123.46
round("123.45");        // Returns 123

Teraz, aby odpowiedzieć na pytanie OP, trzeba wpisać:

round(10.8034, 2).toFixed(2); // Returns "10.80"
round(10.8, 2).toFixed(2);    // Returns "10.80"

Lub, dla bardziej zwięzłego, mniej ogólnego funkcja:

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

Można go nazwać za pomocą:

round2Fixed(10.8034); // Returns "10.80"
round2Fixed(10.8);    // Returns "10.80"

Różne przykłady i testy (dzięki @T-J-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>
 79
Author: astorije,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-27 17:47:45

Zazwyczaj dodaję to do mojej osobistej biblioteki, a po kilku sugestiach i użyciu rozwiązania @ TIMINeutron, i uczynieniu go dostosowanym do długości dziesiętnej, ten pasuje najlepiej:

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

Będzie działać dla zgłoszonych WYJĄTKÓW.

 41
Author: Miguel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-25 08:42:19

Nie wiem dlaczego nie mogę dodać komentarza do poprzedniej odpowiedzi( może jestem beznadziejnie ślepy, Nie wiem), ale wymyśliłem rozwiązanie korzystając z odpowiedzi @ Miguel:

function precise_round(num,decimals) {
   return Math.round(num*Math.pow(10, decimals)) / Math.pow(10, decimals);
}

I jego dwa komentarze (od @bighostkim i @Imre):

  • Problem z precise_round(1.275,2) nie zwraca 1.28
  • Problem z precise_round(6,2) nie zwróceniem 6.00 (jak chciał).

Moje ostateczne rozwiązanie jest następujące:

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

Jak widać musiałem dodać trochę "korekty" (to nie jest to, co jest, ale od matmy.round is lossy - możesz sprawdzić na jsfiddle.net -tylko w ten sposób wiedziałem, jak to "naprawić"). Dodaje 0,001 do już wyściełanej liczby, więc dodaje 1 Trzy 0s na prawo od wartości dziesiętnej. Więc powinien być bezpieczny w użyciu.

Po tym dodałem .toFixed(decimal), aby zawsze wypisywać liczbę w odpowiednim formacie (z odpowiednią ilością miejsc po przecinku).

Więc to tyle. Używaj go dobrze;)

EDIT: dodano funkcjonalność do "korekty" liczby ujemne.

 16
Author: tfrascaroli,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-25 08:44:59

Jeden sposób na 100% pewność, że otrzymasz liczbę z 2 po przecinku:

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

Jeśli spowoduje to błędy zaokrąglania, możesz użyć następującego sposobu, jak James wyjaśnił w swoim komentarzu:

(Math.round((num * 1000)/10)/100).toFixed(2)
 13
Author: Gerard de Visser,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-24 17:35:35

Tofixed (n) podaje n długości po przecinku; toPrecision (x) zapewnia x całkowitą długość.

Użyj tej metody poniżej

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

I jeśli chcesz, aby liczba była stała użyj

result = num.toFixed(2);
 12
Author: Syed Umar Ahmed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-04-17 07:34:59

Nie znalazłem dokładnego rozwiązania tego problemu, więc stworzyłem własne:

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

Przykłady:

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
 5
Author: Florian Ignaz Eßl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-27 08:27:23

@heridev i ja stworzyliśmy małą funkcję w jQuery.

Możesz spróbować dalej:

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

​ DEMO ONLINE:

Http://jsfiddle.net/c4Wqn/

 3
Author: vicmaster,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-27 17:42:13

Problem z wartościami zmiennoprzecinkowymi polega na tym, że próbują reprezentować nieskończoną ilość (ciągłych) wartości o ustalonej ilości bitów. Więc naturalnie, musi być jakaś strata w grze, i będziesz ugryziony z pewnych wartości.

Gdy komputer przechowuje 1.275 jako wartość zmiennoprzecinkową, tak naprawdę nie pamięta, czy był to 1.275, czy 1.274999999999993, czy nawet 1.27500000000002. Wartości te powinny dać różne wyniki po zaokrągleniu do dwóch miejsc po przecinku, ale nie będą, ponieważ dla komputera wyglądają dokładnie tak samo Po zapisaniu jako wartości zmiennoprzecinkowe i nie ma sposobu na przywrócenie utraconych danych. Wszelkie dalsze obliczenia tylko skumulują taką nieprecyzyjność.

Więc jeśli precyzja ma znaczenie, musisz Od początku unikać wartości zmiennoprzecinkowych. Najprostsze opcje to

  • użyj poświęconej biblioteki
  • używaj łańcuchów do przechowywania i przekazywania wartości (wraz z łańcuchem operacje)
  • Możesz przekazywać liczbę setną rzeczywistej wartości, np. kwotę w centach zamiast kwoty w dolarach)

Na przykład, gdy używa się liczb całkowitych do przechowywania liczby setnej, funkcja znajdowania rzeczywistej wartości jest dość prosta:

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

Z ciągami, trzeba będzie zaokrąglać, ale i tak da się to opanować:

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

Zauważ, że funkcja ta jest zbliżona do najbliższej, jest oddalona od zera, podczas gdy IEEE 754 zaleca zaokrąglanie do najbliższego, Wiązanie do parzystego jako domyślne zachowanie operacji zmiennoprzecinkowych. Takie modyfikacje pozostawiamy jako ćwiczenie dla czytelnika:)

 2
Author: Imre,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 11:55:10

Oto prosty

function roundFloat(num,dec){
    var d = 1;
    for (var i=0; i<dec; i++){
        d += "0";
    }
    return Math.round(num * d) / d;
}

Użyj jak alert(roundFloat(1.79209243929,4));

Jsfiddle

 2
Author: ow3n,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-02 14:48:44

Zaokrągl wartość dziesiętną, a następnie użyj toFixed(x) dla oczekiwanych cyfr.

function parseDecimalRoundAndFixed(num,dec){
  var d =  Math.pow(10,dec);
  return (Math.round(num * d) / d).toFixed(dec);
}

Call

Parsedecimalround andfixed(10.800243929,4) => 10.80 parseDecimalRoundAndFixed(10.807243929,2) => 10.81

 2
Author: HATCHA,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-07 05:03:11

Umieść następujące w jakimś globalnym zasięgu:

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

I Następnie spróbuj :

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

Update

Zauważ, że toFixed() może działać tylko dla liczby miejsc po przecinku pomiędzy 0-20, tzn. {[5] } może generować błąd javascript, więc aby uwzględnić, możesz dodać dodatkowe sprawdzenie, tzn.

Number.prototype.getDecimals = function ( decDigCount ) {
   return ( decDigCount > 20 ) ? this : this.toFixed(decDigCount);
}
 1
Author: Kamran Ahmed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-16 07:13:05
Number(((Math.random() * 100) + 1).toFixed(2))

Zwróci to losową liczbę od 1 do 100 zaokrągloną do 2 miejsc po przecinku.

 1
Author: Johnathan Ralls,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-20 20:24:35
Number(Math.round(1.005+'e2')+'e-2'); // 1.01

To działało dla mnie: Zaokrąglanie dziesiętnych w JavaScript

 1
Author: Max G,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-04 12:13:10

Użycie tej odpowiedzi przez odniesienie: https://stackoverflow.com/a/21029698/454827

Buduję funkcję, aby uzyskać dynamiczne liczby dziesiętne:

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

Oto przykład pracy: https://jsfiddle.net/wpxLduLc/

 1
Author: ZiTAL,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:10:48

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>
 1
Author: Vishnu T Asok,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-23 14:06:05

Round down

function round_down(value, decPlaces) {
    return Math.floor(value * Math.pow(10, decPlaces)) / Math.pow(10, decPlaces);
}

Round up

function round_up(value, decPlaces) {
    return Math.ceil(value * Math.pow(10, decPlaces)) / Math.pow(10, decPlaces);
}

Runda najbliższa

function round_nearest(value, decPlaces) {
    return Math.round(value * Math.pow(10, decPlaces)) / Math.pow(10, decPlaces);
}

Połączone https://stackoverflow.com/a/7641824/1889449 i https://www.kirupa.com/html5/rounding_numbers_in_javascript.htm Dzięki oni.

 1
Author: MERT DOĞAN,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-28 13:34:34

Z tymi przykładami nadal pojawi się błąd podczas próby zaokrąglenia liczby 1.005 rozwiązaniem jest użycie biblioteki takiej jak matematyka.js lub ta funkcja:

function round(value: number, decimals: number) {
    return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
}
 1
Author: Dave Webster,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-09 23:09:57

Oto moje rozwiązanie 1-liniowe: Number((yourNumericValueHere).toFixed(2));

Oto co się dzieje:

1) najpierw zastosuj .toFixed(2) na liczbę, której chcesz zaokrąglić miejsca po przecinku. Zauważ, że spowoduje to konwersję wartości na łańcuch znaków z liczby. Więc jeśli używasz maszynopisu, spowoduje to błąd w następujący sposób:

"Type' string 'is not assignable to type 'number' "

2) aby odzyskać wartość liczbową lub przekonwertować łańcuch na wartość liczbową, po prostu zastosuj funkcję Number() na tak zwaną wartość "string".

Dla wyjaśnienia, spójrz na poniższy przykład:

Przykład: Mam kwotę, która ma do 5 cyfr w miejscach po przecinku i chciałbym skrócić go do 2 miejsc po przecinku. Ja tak robię:

var price = 0.26453;
var priceRounded = Number((price).toFixed(2));
console.log('Original Price: ' + price);
console.log('Price Rounded: ' + priceRounded);
 1
Author: Devner,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-25 05:08:45

Kilka miesięcy temu otrzymałem kilka pomysłów z tego postu, ale żadna z odpowiedzi tutaj,ani odpowiedzi z innych postów / blogów nie poradziłaby sobie ze wszystkimi scenariuszami (np. liczby ujemne i niektóre "szczęśliwe liczby", które znalazł nasz tester). W końcu nasz tester nie znalazł żadnego problemu z tą metodą poniżej. Wklejenie fragmentu mojego kodu:

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

Mam też komentarze do kodu (przepraszam, że zapomniałem już o wszystkich szczegółach)...Zamieszczam tutaj swoją odpowiedź na przyszłość:

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).
 1
Author: remondo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-24 06:30:21

Naprawiam problem modyfikatorem. Obsługa tylko 2 dziesiętnych.

$(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>
 0
Author: bamossza,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-20 06:28:38
(Math.round((10.2)*100)/100).toFixed(2)

To powinno dać: 10.20

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

To powinno dać: 0.05

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

To powinno dać: 4.04

Itd.

 0
Author: Anthony Ruffino,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-17 13:04:01

/*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.
*/
 0
Author: Christian Læirbag,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-18 20:55:53

Jest to bardzo proste i działa tak samo dobrze jak wszystkie inne:

function parseNumber(val, decimalPlaces) {
    if (decimalPlaces == null) decimalPlaces = 0
    var ret = Number(val).toFixed(decimalPlaces)
    return Number(ret)
}

Ponieważ tofixed () może być wywołane tylko na liczbach i niestety zwraca łańcuch znaków, to robi wszystkie parsowanie dla Ciebie w obu kierunkach. Możesz przekazać ciąg lub numer, a za każdym razem otrzymasz numer z powrotem! Wywołanie parseNumber(1.49) da ci 1, a parseNumber (1.49,2) da ci 1.50. Tak jak najlepsi!

 0
Author: Aaron Dake,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-19 21:26:14

Możesz również użyć metody .toPrecision() i kodu niestandardowego i zawsze zaokrąglać do n-tej cyfry dziesiętnej niezależnie od długości części int.

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

Możesz również zrobić z niego wtyczkę do lepszego wykorzystania.

 0
Author: leo_lo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-04 12:06:37

/**
 * 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
 0
Author: Amr Ali,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-18 11:05:30

Proste jak to.

var rounded_value=Math.round(value * 100) / 100;
 0
Author: Gihan Gamage,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-25 03:06:50

100% działa!!! 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>
 -4
Author: JONAS MAGALHAES DOS SANTOS,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-18 14:42:02