Trim trailing zeroes
by helgatheviking
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/accounting.js/0.4.1/accounting.min.js"></script>
<label for="test">Enter a price</label><input id="test" class="nyp-input" />
JavaScript
const woocommerce_nyp_params = {
currency_format_decimal_sep: '.',
currency_format_thousand_sep: ',',
currency_format_num_decimals: 2,
currency_format: '%s%v',
trim_trailing_zeroes: true
};
// Format the price with accounting.js.
function woocommerce_nyp_format_price( price, currency_symbol, format ) {
if ( typeof currency_symbol === 'undefined' ) {
currency_symbol = '';
}
if ( typeof format === 'undefined' ) {
format = false;
}
var currency_format = format ? woocommerce_nyp_params.currency_format : '%v';
var formatted_price = accounting.formatMoney(
price,
{
symbol : currency_symbol,
decimal : woocommerce_nyp_params.currency_format_decimal_sep,
thousand: woocommerce_nyp_params.currency_format_thousand_sep,
precision : woocommerce_nyp_params.currency_format_num_decimals,
format: currency_format
}
).trim();
if ( woocommerce_nyp_params.trim_trailing_zeroes ) {
var negative_num_decimals = woocommerce_nyp_params.currency_format_num_decimals * -1
var cents = formatted_price.slice( negative_num_decimals );
if ( 0 === parseFloat( cents ) ) {
formatted_price = formatted_price.slice( 0, negative_num_decimals );
formatted_price = formatted_price.replace( woocommerce_nyp_params.currency_format_decimal_sep, '' );
}
}
return formatted_price;
}
// Get absolute value of price and turn price into float decimal.
function woocommerce_nyp_unformat_price( price ) {
return Math.abs( parseFloat( accounting.unformat( price, woocommerce_nyp_params.currency_format_decimal_sep ) ) );
}
$( 'body' ).on( 'change', '.nyp-input', function(e) {
var raw_price = $(this).val().trim() ? $(this).val().trim() : '';
var user_price = woocommerce_nyp_unformat_price( raw_price );
// Maybe auto-format the input.
if ( '' !== raw_price ) {
$(this).val( woocommerce_nyp_format_price( user_price ) );
}
});