Basil
Basil

Reputation: 23

How to convert numbers with comma to money format

I am trying to convert numbers from a database into money format, using the function money format. The SQL query works fine and the output for

echo "$amount" is 800,600.00.

I have tried using

setlocale(LC_MONETARY, 'en_US');
echo money_format('%i', $amount) . "\n";

but I get the following error:

Fatal error: Uncaught Error: Call to undefined function money_format() in C:\xampp\htdocs\loan\en\account\payment.php:14 Stack trace: #0 {main} thrown in C:\xampp\htdocs\loan\en\account\payment.php on line 14

My overall codes are:

<?php
include('../user/db.php');
$uploaduser = "ruxell4real";
$stmt =$conn->prepare("SELECT * FROM users WHERE username=?");
$stmt->bind_param("s", $uploaduser);
$stmt->execute();
$row = $stmt->get_result();
$result= $row->fetch_assoc();

$amount = $result['balance'];


setlocale(LC_MONETARY, 'en_US');
echo money_format('%i', $amount) . "\n";

Upvotes: 1

Views: 989

Answers (1)

jspit
jspit

Reputation: 7703

Your input is a string of the form "800,600.00". This string cannot be converted into a float in this way. The comma must be removed for this. I use a simple str_replace for this.

$amount = "800,600.00";

$floatAmount = (float)str_replace(",","",$amount);
//test
var_dump($floatAmount);  //float(800600)

This float value can then be output in the required format with the corresponding functions/classes.

echo "number_format: ". number_format($floatAmount,2,".",","). "<br>";

$fmt = new \NumberFormatter("en_US", NumberFormatter::CURRENCY);
echo "NumberFormatter: ".$fmt->format($floatAmount) . "<br>"; 

Output:

number_format: 800,600.00
NumberFormatter: $800,600.00

Upvotes: 3

Related Questions