Matt
Matt

Reputation: 1177

How to add decimals to number?

I need to add decimals to numbers that represent money. I want it to automatically calculate where to add the decimal point, here's an example of what I want, it should explain it better:

Input: $000 Output: $0.00

Input: $151 Output: $1.51

Input: $20300 Output: $203.00

Upvotes: 0

Views: 172

Answers (1)

RhapX
RhapX

Reputation: 1683

Since your numbers are starting without decimals, you will have to assume that the last two numbers of the string are your interests.

You could create a simple function to convert your numbers under the assumption of the last two characters being the decimal places.

$number = 20300;

function convertToDecimal($number) {

    if( $number == 0 ) {
        return number_format($number, 2);
    }

    $beginning = substr($number, 0, -2);
    $end       = substr($number, -2);

    return $beginning . '.' . $end;

}

echo convertToDecimal($number);

Returns: 203.00

Upvotes: 3

Related Questions