Domanda

Ho questa riga di codice che arrotonda i miei numeri a due cifre decimali.Ma ottengo numeri come questo:10.8, 2.4, ecc.Queste non sono la mia idea di due cifre decimali, quindi come posso migliorare quanto segue?

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

Voglio numeri come 10.80, 2.40, ecc.L'uso di jQuery va bene per me.

È stato utile?

Soluzione

Per formattare un numero utilizzando la notazione a virgola fissa, puoi semplicemente utilizzare il comando aFisso metodo:

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

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

Notare che toFixed() restituisce una stringa.

IMPORTANTE:Tieni presente che toFixed in realtà non arrotonda, il 90% delle volte restituirà il valore arrotondato ma in molti casi in realtà non funziona.Prova questo nella tua console:

2.005.toFixed(2)

Riceverai la risposta sbagliata

Non esiste un modo naturale per ottenere un arrotondamento decimale in Javascript, avrai bisogno del tuo polyfill o utilizzerai una libreria.Puoi guardare il polyfill di Mozilla per questo https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round

Altri suggerimenti

Questo è un argomento vecchio, ma ancora top-ranked risultati di Google e le soluzioni di condivisione offerto lo stesso in virgola mobile decimali problema. Ecco la funzione (molto generico) che uso, grazie a 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));
}

Come si vede, non otteniamo questi problemi:

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

Questa genericità fornisce anche alcune cose interessanti:

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

Ora, per rispondere alla domanda del PO, si deve digitare:

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

In alternativa, per una funzione meno generico più concisa:

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

Si può chiamare con:

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

Vari esempi e test (grazie a @ 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>

Io di solito aggiungere questo alla mia biblioteca personale, e dopo alcuni suggerimenti e utilizzando la soluzione @TIMINeutron troppo, e che lo rende adattabile per la lunghezza decimale, allora, questo si adatta meglio:

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

funzionerà per le eccezioni segnalate.

Non so il motivo per cui non riesco ad aggiungere un commento ad una risposta precedente (forse sono irrimediabilmente cieco, dunno), ma mi si avvicinò con una soluzione che utilizza @ risposta di Miguel:

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

E i suoi due commenti (da @bighostkim e @Imre):

  • Problema con precise_round(1.275,2) non tornare 1.28
  • Problema con precise_round(6,2) non tornare 6.00 (come voleva).

La mia soluzione finale è la seguente:

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

Come potete vedere ho dovuto aggiungere un po 'di "correzione" (che non è quello che è, ma dal momento che è Math.round lossy - è possibile verificare su jsfiddle.net - questo è l'unico modo che conoscevo per risolverlo). Aggiunge 0.001 al numero già imbottito, per cui è l'aggiunta di un 1 tre 0s alla destra del valore decimale. Così dovrebbe essere sicuro da usare.

Dopo che ho aggiunto al .toFixed(decimal) sempre in uscita il numero nel formato corretto (con la giusta quantità di cifre decimali).

In modo che sia praticamente. Usarlo bene;)

EDIT:. Aggiunto funzionalità al "correzione" dei numeri negativi

Un modo per essere sicuri al 100% che si ottiene un numero con 2 decimali:

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

Se questo provoca errori di arrotondamento, è possibile utilizzare il seguente come James ha spiegato nel suo commento:

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

toFixed (n) prevede lunghezza n dopo il punto; toPrecision (x)   fornisce x lunghezza totale.

Utilizzare questo metodo seguente

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

E se si desidera che il numero da fissare uso

result = num.toFixed(2);

non ho trovato una soluzione precisa per questo problema, così ho creato il mio:

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

Esempi:

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 e ho creato una piccola funzione in jQuery.

Si può provare successivo:

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

ONLINE DEMO:

http://jsfiddle.net/c4Wqn/

Ecco un semplice

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

Usa come alert(roundFloat(1.79209243929,4));

Jsfiddle

Il problema di valori in virgola mobile è che stanno cercando di rappresentare una quantità infinita di valori (continue) con una quantità fissa di bit. Così, naturalmente, ci deve essere qualche perdita in gioco, e si sta andando ad essere morso con alcuni valori.

Quando un computer memorizza 1.275 come un valore in virgola mobile, sarà in realtà non ricordo se era 1.275 o 1,27499999999999993, o addirittura 1,27500000000000002. Questi valori dovrebbero dare risultati diversi dopo l'arrotondamento a due decimali, ma non lo faranno, in quanto per il calcolatore si guardano esattamente la stessa dopo aver memorizzato come valori in virgola mobile, e non c'è modo di ripristinare i dati persi. Eventuali ulteriori calcoli si accumulano solo ad imprecisioni.

Quindi, se le cose di precisione, si deve evitare di valori in virgola mobile fin dall'inizio. Le opzioni più semplici sono a

  • dedicato biblioteca
  • uso stringhe per memorizzare e passando attorno ai valori (accompagnata da operazioni di stringa)
  • uso di numeri interi (ad esempio, si potrebbe essere passando intorno alla quantità di centesimi di tuo valore reale, per esempio importo in centesimi, invece di importo in dollari)

Ad esempio, quando si utilizza numeri interi a memorizzare il numero di centesimi, la funzione per trovare il valore reale è molto semplice:

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

Con le stringhe, avrete bisogno di arrotondamento, ma è ancora gestibile:

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

Si noti che questa funzione arrotonda al più vicino, legami di distanza da zero , mentre IEEE 754 raccomanda arrotondamento al più vicino, legami anche come il comportamento predefinito per operazioni in virgola mobile. Tali modifiche sono lasciati come esercizio per il lettore:)

rotonda vostro valore decimale, quindi utilizzare toFixed(x) per la cifra prevista (s).

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

Chiama

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

Qui è la mia soluzione 1-line: Number((yourNumericValueHere).toFixed(2));

Ecco cosa succede:

1) In primo luogo, si applica .toFixed(2) sul numero che si desidera arrotondare i decimali di. Si noti che questo convertire il valore in una stringa a partire dal numero. Quindi, se si sta utilizzando tipografico, getterà un errore come questo:

" 'stringa' Tipo non è assegnabile al tipo 'numero'"

2) Per recuperare il valore numerico o per convertire la stringa in valore numerico, è sufficiente applicare la funzione Number() su quel cosiddetto valore 'stringa'.

Per chiarimenti, guardare l'esempio qui sotto:

Esempio: Ho un importo che ha fino a 5 cifre nei decimali e mi piacerebbe accorciare a fino a 2 cifre decimali. Lo faccio in questo modo:

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

Mettere il seguente in qualche ambito globale:

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

e quindi provare :

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

Aggiornamento

Si noti che toFixed() può funzionare solo per il numero di decimali tra 0-20 cioè a.getDecimals(25) può generare un errore di javascript, in modo da accogliere che si può aggiungere qualche ulteriore cioè di controllo.

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

questo restituirà un numero casuale da 1 a 100 arrotondato a 2 cifre decimali.

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

Questo ha funzionato per me: arrotondamento dei decimali in JavaScript

Utilizzando questa risposta con riferimento: https://stackoverflow.com/a/21029698/454827

costruisco una funzione per ottenere i numeri dinamici di decimali:

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

esempio qui a lavorare: 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>

Per concludere giù

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

rotonda più vicina

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 Grazie   loro.

Con questi esempi si continua a ottenere un errore quando si cerca di arrotondare il numero di 1.005 la soluzione è usare sia per una libreria come Math.js o questa funzione:

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

Ho alcune idee da questo post di qualche mese fa, ma nessuna delle risposte qui, né risposte da altri messaggi / blog potuto gestire tutti gli scenari (ad esempio i numeri negativi e alcuni "numeri fortunati" nostro tester trovato). Alla fine, il nostro tester non ha trovato alcun problema con questo metodo di seguito. Incollare un frammento del mio codice:

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

Ho anche commenti del codice (scusate ho dimenticato già tutti i dettagli) ... sto postando la mia risposta qui per riferimento futuro:

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

Sono risolvere il problema il modificatore. Supporto 2 decimali solo.

$(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)

Questo dovrebbe produrre: 10.20

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

Questo dovrebbe produrre: 0.05

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

Questo dovrebbe produrre: 4.04

ecc.

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

Questo è molto semplice e funziona altrettanto bene come tutti gli altri:

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

Dal toFixed () può essere chiamato solo sui numeri, e restituisce una stringa purtroppo, questo fa tutto il parsing per voi in entrambe le direzioni. È possibile passare una stringa o un numero, e si ottiene ogni volta un numero indietro! Chiamata parseNumber (1.49) vi darà 1, e parseNumber (1.49,2) vi darà 1,50. Proprio come il meglio del 'em!

Si potrebbe anche utilizzare il metodo .toPrecision() e codice personalizzato, e sempre arrotondare fino alla cifra decimale ennesima indipendentemente dalla lunghezza della parte int.

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

Si potrebbe anche fare un plugin per un migliore utilizzo.

semplice come questo.

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

Ho trovato un modo molto semplice che ha risolto questo problema per me e può essere utilizzato o adattati:

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

100% di lavoro !!! Provalo

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top