2009-11-11 14 views
5

Esiste una funzione incorporata di JavaScript per convertire una stringa in un formato di valuta?Converti in formato valuta

Per esempio

var a = '1234'; 
a.convertToCurrency(); // return $1,234 

UPDATE

Si prega di notare che voglio la funzione per tornare alla moneta di includere la virgola degli Stati Uniti per le cifre del gruppo.

+0

FWIW c'è ora un costruito in funzione in JavaScript che fa questo: https://developer.mozilla.org/en-US/docs/Web/ JavaScript/Riferimento/Global_Objects/NumberFormat, che funziona anche nel nodo - come da 0.12 – Simon

risposta

4
var a = 1234.12; 
var c = '$' + a.toLocaleString(); 
+1

Questo non aggiunge "," (virgole) – TimH

+0

Il tuo esempio restituisce $ 1234.12 ma voglio restituire $ 1,234 – TimH

+0

Sfortunatamente dipende dal tuo Impostazioni di sistema. – ChaosPandion

0

Questo abbiamo fatto in un nostro progetto molto tempo fa. Ho appena trovato il codice. La nostra applicazione era in asp.net. Funzione dollarAmount fa il lavoro

function checkNum(data) {  // checks if all characters 
     var valid = ".";  // are valid numbers or a "." 
     var ok = 1; var checktemp; 
     for (var i=0; i<data.length; i++) { 
     checktemp = "" + data.substring(i, i+1); 
     if (valid.indexOf(checktemp) == "-1") return 0; } 
     return 1; 
    } 

    function dollarAmount(form, field, appendZero) 
    { 
     Num = "" + eval("document." + form + "." + field + ".value"); 

     if(Num=="") 
     { 
      eval("document." + form + "." + field + ".value = '" + 0 + "';"); 
      return; 
     } 

     dec = Num.indexOf("."); 

     end = ((dec > -1) ? "" + Num.substring(dec,Num.length) : ""); 

     Num = "" + parseInt(Num); 

     var temp1 = ""; 
     var temp2 = ""; 
     //var appendZero=1; 

     if (checkNum(Num) == 0) { 
     //alert("This does not appear to be a valid number. Please try again."); 
     } 
     else { 

      if(appendZero==1 || end !="") 
      { 
       if (end.length == 2) end += "0"; 
       if (end.length == 1) end += "00"; 
       if (end == "") end += ".00"; 
      } 

     var count = 0; 
     for (var k = Num.length-1; k >= 0; k--) { 
     var oneChar = Num.charAt(k); 
     if (count == 3) { 
     temp1 += ","; 
     temp1 += oneChar; 
     count = 1; 
     continue; 
     } 
     else { 
     temp1 += oneChar; 
     count ++; 
     } 
     } 
     for (var k = temp1.length-1; k >= 0; k--) { 
     var oneChar = temp1.charAt(k); 
     temp2 += oneChar; 
     } 
     temp2 = temp2 + end; 
     eval("document." + form + "." + field + ".value = '" + temp2 + "';"); 
     } 
    } 

Abbiamo chiamato questa funzione come questa

txtBox.Attributes.Add("OnBlur", "return DollarAmount('" + txtBox.ID + "',0)"); 

Anche dopo googling ho trovato questo collega

una) Use JavaScript to Format Currency within Your Web Page

b) Currency Format

Inoltre immagino che JQuery può avere qualche plug-in per servire allo scopo Currency: an unobstrusive automatic and real time currency conversion

ma dubito qualsiasi funzione intrinseca è disponibile in javascript. Per favore fatemi sapere se ne avete trovato. Mi piacerebbe saperlo.

Grazie.

+0

Non è necessario utilizzare eval .... document.forms [nome_file] [nome_campo] .valore – ChaosPandion

14

ho deciso di riscrivere completamente esempio ho fatto nel 2009. Si prega di verificare diff se interessati a più vecchia versione. Per ottenere funzionalità come la risposta precedente, ho estratto una parte della libreria Money su cui sto lavorando.

Inoltre non ricordo perché ho ricreato l'ultima volta toFixed come quel metodo era già presente. Questa volta non è incluso.

Invece di fare scherzi con String e Number oggetti in JavaScript, come l'ultima volta, io creo nuovi, Money, oggetto.

(function() { 
    window.Money = (function() { 

    Money.prototype.amount = 0.0; 
    Money.prototype.fraction_count = 2; 
    Money.prototype.fraction_separator = ","; 
    Money.prototype.separate_thousands = true; 
    Money.prototype.symbol = "€"; 
    Money.prototype.symbol_position = "front"; 
    Money.prototype.symbol_spacing = false; 
    Money.prototype.thousands_separator = "."; 

    function Money(amount, options) { 
     var o; 
     if (options == null) { 
     options = {}; 
     } 
     for (o in options) { 
     this[o] = options[o]; 
     } 
     amount = parseFloat(amount); 
     if (!isNaN(amount)) { 
     this.amount = amount; 
     } 
     this.format(); 
    } 

    Money.prototype.format = function() { 
     this.string_amount = this.amount.toFixed(this.fraction_count); 
     if (this.separate_thousands) { 
     this.string_amount = this.separateThousands(); 
     } 
     return this.string = this.addSymbol(); 
    }; 

    Money.prototype.separateThousands = function() { 
     var after_dot, before_dot, pattern, _ref; 
     _ref = this.string_amount.split("."), before_dot = _ref[0], after_dot = _ref[1]; 
     pattern = /(-?\d+)(\d{3})/; 
     while (pattern.test(before_dot)) { 
     before_dot = before_dot.replace(pattern, "$1" + this.thousands_separator + "$2"); 
     } 
     return [before_dot, after_dot].join(this.fraction_separator); 
    }; 

    Money.prototype.addSymbol = function() { 
     var string; 
     string = [this.string_amount]; 
     string.splice((this.symbol_position === "front" ? 0 : 1), 0, this.symbol); 
     return string.join(this.symbol_spacing ? " " : ""); 
    }; 

    return Money; 

    })(); 

Ora, ho bisogno di modificare e/o NumberString oggetti con dimensioni leggermente e aggiungere toMoney metodo.

Number.prototype.toMoney = function(options) { 
    return new Money(this, options); 
}; 

String.prototype.toMoney = function(options) { 
    return new Money(this, options); 
}; 

Così, finalmente, possiamo convertire String e/o Number-Money e scriverlo fuori come String di nuovo.

x = "1234567890.0987654321".toMoney(); 
y = 1234567890.0987654321.toMoney({fraction_count: 5, symbol: "$", symbol_position: "back"}); 

console.log(x); 
// Money {amount: 1234567890.0987654, string_amount: "1.234.567.890,10", string: "€1.234.567.890,10"} 

console.log(x.string) 
// €1.234.567.890,10 

console.log(y); 
// Money {fraction_count: 5, symbol: "$", symbol_position: "back", amount: 1234567890.0987654, string_amount: "1.234.567.890,09877"…} 

console.log(y.string) 
// 1.234.567.890,09877$ 

Penso che questa soluzione sia molto meglio dell'ultima che ho scritto. Per esempio di lavoro controllare jsFiddle.

+0

Sembra avere un errore: 0,5 formati come "0,5", non "0,50" (la valuta deve essere di 2 decimali non uno) –

+1

Ho fissato la frazione se il numero decimale non ha abbastanza posti. ** Modifica: ** '$ A.arr [1] == indefinito? $ A._dec = $ O.use_fractions.fraction_separator + "0" .times ($ O.use_fractions.fractions): $ A._dec = $ O.use_fractions.fraction_separator + $ A.arr [1]; ' * * A: ** '$ A.arr [1] == indefinito? $ A._dec = $ O.use_fractions.fraction_separator + "0" .times ($ O.use_fractions.fractions): $ A._dec = $ O.use_fractions.fraction_separator + $ A.arr [1] + "0". times ($ O.use_fractions.fractions - $ A.arr [1] .length); ' –

+0

Ho fatto una piccola riscrittura, penso che questa versione sia migliore. – Krule

1

Sembra molto lavoro solo per analizzare una stringa e capire dove mettere le virgole.

Ecco un piccolo script che ho messo insieme questa mattina che farà il trucco per i numeri interi:

Chiamare la funzione numberToCurrency e superare il tuo valore come (quantità), che verrà messo le virgole dove dovrebbero essere.

<!DOCTYPE html> 
<head> 
<meta charset="utf-8"> 
<title>Number to Money Conversion</title> 
<script> 
    function numberToCurrency(amount) { 

     var thousandsSeparator = "," 
     var currencyNum = ""; 
     var amountString = amount.toString(); 
     var digits = amountString.split(""); 

     var countDigits = digits.length; 
     var revDigits = digits.reverse(); 

     for(var i=0; i<countDigits; i++) { 
      if ((i%3 == 0) && (i !=0)) { 
       currencyNum += thousandsSeparator+revDigits[i]; 
      } else { 
       currencyNum += digits[i]; 
      } 
     }; 

     var revCurrency = currencyNum.split("").reverse().join(""); 

     var finalCurrency = "$"+revCurrency; 

     return finalCurrency; 
    } 
</script> 
</head> 
<body> 

<script> 
document.write(numberToCurrency('1238868934324')); 
</script> 


</body> 
</html> 

Si può agire su questo in un ciclo di prendere le variabili, come pure - ho buttato insieme un grafico a barre in pila in Raphael che ha le descrizioni dei comandi che visualizzano gli importi in dollari formattati, tratti da numeri dritto in una matrice, così ho don 'Devo smanettare con tutte le citazioni' n 'tali. A parte gli sfondi a bolle nere che vengono progressivamente disallineati quando passo il mouse sopra le pile in ogni barra, funziona piuttosto bene - continuando a riscontrare problemi con le etichette - l'etichettatrice sembra avere problemi. Solo un esempio di prova, davvero, ma per convertire i numeri in valuta, fa il trucco.

Ho anche fatto uno script che rileva per centesimi e aggiunge uno "0" se c'è solo una cifra dopo il ".", Ma non l'ho provato così ampiamente, e ci sono numerosi test diversi che potrei immagina che avresti bisogno di fare in aggiunta. Pubblicherò brevemente la copia di lavoro e potrai giocarci.

Ecco quello che ho fatto con Raphael: http://lifeistryingtotellyousomething.info/raphael/raphael-stacked-column-demo-2000.html

1

Ecco un altro approccio che rappresenta centesimi:

<!DOCTYPE html> 
<head> 
<meta charset="utf-8"> 
<title>Money Conversion</title> 

<script type="text/javascript"> 
function numberToCurrency(amount) { 

    var wholeDigits; 
    var thousandsSeparator = "," 
    var centSeparator = "." 
    var currencyNum = ""; 

    if(amount.indexOf(".") != -1) { 
     var hasCents = true; 
    } else { 
     var hasCents = false; 
    } 

    if (hasCents == true) { 
     var num = amount.split("."); 
     var wholeDigits = num[0].split(""); 
     var centAmount = num[1]; 
     var centDigits = num[1].split(""); 

     if (centDigits.length == 0) { 
      centDigits += "00"; 
     } 
     if ((centDigits.length > 0) && (centDigits.length < 2)) { 
      centDigits += "0"; 
     } 

    } else { 
     centDigits = ""; 
     centSeparator = ""; 
     wholeDigits = amount.split(""); 
    } 

    var countDigits = wholeDigits.length; 

    var revDigits = wholeDigits.reverse(); 

    for(var i=0; i<countDigits; i++) { 
      if ((i%3 == 0) && (i !=0)) { 
       currencyNum += thousandsSeparator+revDigits[i]; 
      } else { 
       currencyNum += wholeDigits[i]; 
      } 
    }; 

    var revCurrency = currencyNum.split("").reverse().join(""); 

    var finalCurrency = "$"+revCurrency+centSeparator+centAmount; 

    return finalCurrency; 
} 
</script> 

</head> 
<body> 


<script type="text/javascript"> 

document.write(numberToCurrency('12326563523.37')); 

</script> 

</body> 
</html> 

Lo fa il trucco, anche se non arrotondare gli importi centesimo o nastri off extra passato 2 cifre.

0

Anche se questo è un vecchio post. Tuttavia, questo ha lavorato in per me nel mio caso:

var a = parseInt("1234"); 
console.log("$"+number_format(a)); 

var number_format = function(total) { 
    return total.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'); 
}; 
Problemi correlati