Jump to content

Format table according to data type


lordterrin

Recommended Posts

Coming from the world of Excel, I can easily format numbers as $1,500.00, or 27%.  When I uploaded a large chunk of data into SQL to be read back through a table, the values all come out as exactly what they were uploaded as.  For example, I have an SQL column set as Decimal(19,4) that I want formatted like currency, but which shows up as 1500.0000 in my table, or another column with type decimal(5,2) which shows up as 5500.0000, but which I want to show up as 55%.  How do I do this?

Link to comment
https://forums.phpfreaks.com/topic/290830-format-table-according-to-data-type/
Share on other sites

Yeah - I could always

 

DECIMAL(5,2) for a percentage? Wtf?

printf, sprintf, or number_format, possibly with a little bit of math (like some division) will do what you need.

 

Yeah I guess I could change that - when I set the type I didn't think it was going to be for percentages.  How would I go about using printf or number_format in the following string?

 

 

while($row = mysqli_fetch_array($result)) {
 
echo "<td>" . $row['RGP'] . "</td>";
 
}

Check the documentation to see what the different functions do. sprintf() will format to a string, printf() will output it instead, and number_format() will format a number to be more human-readable.

 

If the number is 5500.0 and you want 55% then you divide by 100, round, and format with a percent sign. You don't even need any of those three functions for it

echo "" . round($row['RGP'] / 100) . "%";
but for a demonstration,

echo "" . sprintf("%.0f%%", $row['RGP'] / 100) . ""; // %f for floating-point, .0 for no decimal places
If you wanted decimal places, those functions are easier to work with:

echo "" . sprintf("%.02f%%", $row['RGP'] / 100) . ""; // .02 for two decimal places: 55.00%

This was really helpful pointing me in the right direction - I've been reading for a few hours now on these different "print" types and they're really interesting.  I just wanted to say thank you for your help :)  I finally settled on the below:

 

 

echo "<td>$" . number_format($row['Reg'],0) . "</td>";

 

to format my currencies.  Your solution works fine for percentages.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.