How display the spell out of an amount with currency details in WooCommerce

Viewed 39

I am trying to spell out WooCommerce order total amount, in my invoice.php template file can reach order total amount.

First I tried:

$total = $order->get_total();
<?php echo ( $total ); ?> - 

<?php 
$f = new NumberFormatter("en", NumberFormatter::SPELLOUT);
echo $f->format($total); ?>  

The order total displayed is 225.00 and the spell out display is: two hundred twenty-five


Edit:

I found the following solution:

<?php  $number = $order->get_total() ;

$formatter = new NumberFormatter('tr', NumberFormatter::SPELLOUT);

$formatter->setTextAttribute(NumberFormatter::DEFAULT_RULESET, "%financial");

echo $formatter->format($number); ?>

But the result shows like that: two hundred twenty-five

The desired display should be: two hundred twenty-five turkish liras , zero penny.

How can i do this ?

1 Answers

The NumberFormatter SPELLOUT constant doesn't handle the decimals.

You can use the following custom function to display a float number amount spell out like (with the currency details):

function wc_spellout_amount( $amount, $country_code = 'tr' ) {
    $formatter = new NumberFormatter($country_code, NumberFormatter::SPELLOUT);
    $formatter->setTextAttribute(NumberFormatter::DEFAULT_RULESET, "%financial");

    $amounts = explode('.', (string) $amount); // Separating decimals from amount

    $output  = $formatter->format($amounts[0]);
    $output .= ' ' . _n('turkish lira', 'turkish liras', $amounts[0], 'woocommerce');
    $output .= ', ' . $formatter->format($amounts[1]);
    $output .= ' ' . _n('penny', 'pennies', ( $amounts[1] > 0 ? $amounts[1] : 1 ), 'woocommerce');

    return $output;
}

Code goes in functions.php file of the active child theme (or active theme).

Usage: Then you will use it as follows in your code:

echo wc_spellout_amount( $order->get_total() );

Tested and works.

Related