Skip to content
Advertisement

How can I fix spellout in php

Good day everyone. I have a problem regards on my code. I’m trying to make a simple program that converts numbers into words but I’ve encountered some issue below is my code.

$num = 900.00;
$exp = explode('.', $num);
$f = new NumberFormatter("en_US", NumberFormatter::SPELLOUT);
$num_words = ucfirst($f->format($exp[0])) . ' point ' . ucfirst($f->format($exp[1]));

Im expecting an output of

Nine hundread

And here’s I got

Nine hundred point Zero

And here’s the error

Notice: Undefined offset: 1

Can someone help me with this. Im struggling to find an answer. Thank you everyone

Advertisement

Answer

You need to use if else like this to check the number behind the point. If it’s zero or less than 1, don’t use point word

$num = floatval(900.00);
$exp = explode('.', $num);
$f = new NumberFormatter("en_US", NumberFormatter::SPELLOUT);
// check the number if the number behind point/comma is less than 1
if(count($exp) == 1){
    $num_words = ucfirst($f->format($exp[0]));
}else{
// other than that print with point
    $num_words = ucfirst($f->format($exp[0])) . ' point ' . ucfirst($f->format($exp[1]));
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement