In jQuery, qual è il modo migliore per formattare un numero con 2 cifre decimali?
-
20-08-2019 - |
Domanda
Questo è quello che ho adesso:
$("#number").val(parseFloat($("#number").val()).toFixed(2));
Mi sembra disordinato. Non penso di concatenare correttamente le funzioni. Devo chiamarlo per ogni casella di testo o posso creare una funzione separata?
Soluzione
Se lo stai facendo in diversi campi, o lo fai abbastanza spesso, allora forse un plug-in è la risposta.
Ecco gli inizi di un plugin jQuery che formatta il valore di un campo con due cifre decimali.
Viene attivato dall'evento onchange del campo. Potresti voler qualcosa di diverso.
<script type="text/javascript">
// mini jQuery plugin that formats to two decimal places
(function($) {
$.fn.currencyFormat = function() {
this.each( function( i ) {
$(this).change( function( e ){
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixed(2);
});
});
return this; //for chaining
}
})( jQuery );
// apply the currencyFormat behaviour to elements with 'currency' as their class
$( function() {
$('.currency').currencyFormat();
});
</script>
<input type="text" name="one" class="currency"><br>
<input type="text" name="two" class="currency">
Altri suggerimenti
Forse qualcosa del genere, dove potresti selezionare più di un elemento se lo desideri?
$("#number").each(function(){
$(this).val(parseFloat($(this).val()).toFixed(2));
});
Modifichiamo una funzione Meouw da utilizzare con il keyup, perché quando si utilizza un input può essere più utile.
Controlla questo:
Hey there !, @heridev e ho creato una piccola funzione in jQuery.
Puoi provare dopo:
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
});
});
& # 8203; DEMO ONLINE:
(@heridev, @vicmaster)