Comma separated numeric values - PHP CodeIgniter - php

How would I echo the numeric values as comma separated
foreach($report_value as $value):
echo round($value['report_total_cost_usd'],2); // ex: 1,234,456.00
endforeach;

This is what you are looking for number_format
echo number_format($value['report_total_cost_usd'], 2, '.', ','); // ex: 1,234,456.00
Output
1,234,456.00
need some dedication towards the work, and some knowledge how to read manuals..

MySQL Solution:
Use format function on the number with an input for decimal places.
Example:
mysql> select format( 1234456, 2 );
+----------------------+
| format( 1234456, 2 ) |
+----------------------+
| 1,234,456.00 |
+----------------------+
You can read the same as string from your scripting language and use.
Refer to:
MySQL: FORMAT(X,D[,locale])
Formats the number X to a format like '#,###,###.##', rounded to D
decimal places, and returns the result as a string. If D is 0, the
result has no decimal point or fractional part.

Try this one
foreach($report_value as $value)
{
echo number_format($value['report_total_cost_usd'],2,'.', ','); // ex: 1,234,456.00
}

Related

How to change in mysql datatype float dot to comma?

In my mysql database I have a column with float datatype and with length 10,2.
When I put the data in database in row it looks like this:
2,589.20
In my country, Serbia, visually will need to look like this:
2.589,20
(first dots, then comma).
When I use it in "value" of form (input) the number_format($number, 2, '.', ',') then I can put the $number in the database, but if it's a number_format($faktura_cenanasa, 2, ',', '.') in "value" then I can't put it in database because of a wrong format of the "value". This problem is only when I reload the data in form, when a reload it somewhere else on site it't not a problem (when I print it on screen).
number_format due to rounding can return misleading output especially for large numbers.
for instance
echo number_format( 1000000000000000000.00952, 2 );
// output: 1,000,000,000,000,000,000.00
echo number_format( 9999999999999999999.00952, 2 );
// output: 10,000,000,000,000,000,000.00
echo number_format( 999999999999999999999999999.00952, 2 );
// output: 1,000,000,000,000,000,013,287,555,072.00
Alternatively like #aynber wrote in a comment you should add one more aliased column or replace the number column with FORMAT in your query
SELECT ..., FORMAT( `number`, 2, 'de_DE' ) AS `formatted_number`
FROM ...
Before replacing the locale to Serbian (in the example is 'de_DE') you should check that it is available into Mysql Locale Support
Additionally just in case make sure that the formatted output is what you expect. There might be a case where your result will be something like the following, instead both should have the same format.
SELECT FORMAT(12500000000000.2015, 2,'de_DE'), FORMAT(12500000000000.2015, 2,'el_GR');
+----------------------------------------+----------------------------------------+
| FORMAT(12500000000000.2015, 2,'de_DE') | FORMAT(12500000000000.2015, 2,'el_GR') |
+----------------------------------------+----------------------------------------+
| 12.500.000.000.000,20 | 12500000000000,20 |
+----------------------------------------+----------------------------------------+
update
When you receive the number formatted- well not a number anymore instead a string- you will be able to edit it as you are please. But, before storing it back to the database you will need to remove all thousand separators and then change the decimal point to '.', i.e
$number = str_replace( [ '.', ',' ], ['', '.'], $number );
Finally insert and this is it.

How to get rupees and paise in separate columns from the amount

The database value for my project will be TOTAL AMOUNT like "1500.45". What I want is to separate the column for Rupees & Paise. 1500 should be under Rupees column, and paise 45 should be under paise column. How to do that?
Output should be like this
|amount | | rupees | paise |
|1500.45| ==> | 1500 | 45 |
simply using split comment to separate rupees and paise..
<?
$RS=2300.75;
$df=split("[.]",$RS);
echo "rupees ".$df[0];
echo "<br>";
echo "paise ".$df[1];
?>
for more details see the link php code for rupees and paise
If you need two need for two decimal points then use the following code :
$amount = 1500.45; // if it is a string then convert it into decimal
$rupee = floor($amount);
$paise = (int)($amount - $rupee)*100; // and set pricision two
echo $rupee.'<br/>';
echo $paise;
and if it string or decimal any type then you can use the code as follows :
$amount = 1500.45;
$rupee = explode('.',$amount)[0];
echo $rupee.'<br/>';
echo explode('.',$amount)[1];
Use explode() Function .
explode(".",your amount)
explode will separate your amount to get Rupees & Paise .
You will get separated value in array using that array you can store bot values in separate columns .
use SUBSTRING_INDEX() to split values in mysql then update
UPDATE `table` SET `rupees`=SUBSTRING_INDEX(`amount`,'.',1),`paise`=SUBSTRING_INDEX(`amount`,'.',2)
Select substring_index('amount', '.', 1) as rupees, substring_index('amount', '.', -1) as paise;

How to convert a string '010101010' into a real binary string, in PHP

I want to store IP addresses into MySQL VARBINARY(16). I've got the binary address as a string '01001010010100101001010010100101'.
When I insert it into MySQL. I realize this will not be converted automatically.
After searching PHP manual, I'm surprised that there is no function for this.
Need your help on how to convert the binary string to VARBINARY.
In PHP you can use bindec and long2ip to convert binary string to IPv4 address:
bindec - Returns the decimal equivalent of the binary number represented by the binary_string argument.
long2ip - Converts an long integer address into a string in (IPv4) Internet standard dotted format
$ip_as_int = bindec('01001010010100101001010010100101');
$ipv4 = long2ip ( $ip_as_int );
echo $ipv4;
74.82.148.165
Thanks you all! But I think I've found a better solution: someone posted at PHP manual page 6 years ago:
http://php.net/manual/en/function.pack.php#93085
<?php
function bin2bstr($input)
// Convert a binary expression (e.g., "100111") into a binary-string
{
if (!is_string($input)) return null; // Sanity check
// Pack into a string
return pack('H*', base_convert($input, 2, 16));
}
function bstr2bin($input)
// Binary representation of a binary-string
{
if (!is_string($input)) return null; // Sanity check
// Unpack as a hexadecimal string
$value = unpack('H*', $input);
// Output binary representation
return base_convert($value[1], 16, 2);
}
// Returns string(3) "ABC"
var_dump(bin2bstr('01000001 01000010 01000011'));
// Returns string(24) "010000010100001001000011"
var_dump(bstr2bin('ABC'));
?>
You can accomplish this by combining funtions inet_ntoa and conv.
mysql> select inet_ntoa(conv('01001010010100101001010010100101',2,10));
+----------------------------------------------------------+
| inet_ntoa(conv('01001010010100101001010010100101',2,10)) |
+----------------------------------------------------------+
| 74.82.148.165 |
+----------------------------------------------------------+
1 row in set (0.00 sec)
More over, the string result can be converted to BINARY:
mysql> select CAST(inet_ntoa(conv('01001010010100101001010010100101',2,10)) AS BINARY);
+--------------------------------------------------------------------------+
| CAST(inet_ntoa(conv('01001010010100101001010010100101',2,10)) AS BINARY) |
+--------------------------------------------------------------------------+
| 74.82.148.165 |
+--------------------------------------------------------------------------+
1 row in set (0.00 sec)
Also this BINARY string can be easily put into VARBINARY(16) column using a UPDATE or INSERT.

PHP & MySQL - Generate invoice number from an integer from the database

I need to generate an invoice number from an integer of a table with an auto incrementing ID of the database where the user purchases saved.
Example of the table invoice database:
The invoice number format floor do one of two ways.
Example 1: of the number of invoices without prefix:
0000001 |
0000002 |
0000003 |
0000004 |
0000005
Example 2: the number of invoices with prefixes:
F-0000001 |
F-0000002 |
F-0000003 |
F-0000004 |
F-0000005
Question:
1) ¿What is the best way to do this, you can do directly from MySQL or PHP?
2) ¿What is the most appropriate format Example 1 or Example 2?
I appreciate your support as always!
Thanks to Gordon Linoff, I could get a way to solve this.
I will share an example, perhaps someone may be interested.
SQL - Invoice without prefix: SELECT id, LPAD(id,7,'0') FROM invoice WHERE id = 1;
Result: 0000001
SQL - Invoice with prefix: SELECT id, CONCAT( 'F-', LPAD(id,7,'0') ) FROM invoice;
Result: F-0000001
You can write a good helper function in PHP to use it wherever you want in your application to return an invoice number. The following helper function can simplify your process.
function invoice_num ($input, $pad_len = 7, $prefix = null) {
if ($pad_len <= strlen($input))
trigger_error('<strong>$pad_len</strong> cannot be less than or equal to the length of <strong>$input</strong> to generate invoice number', E_USER_ERROR);
if (is_string($prefix))
return sprintf("%s%s", $prefix, str_pad($input, $pad_len, "0", STR_PAD_LEFT));
return str_pad($input, $pad_len, "0", STR_PAD_LEFT);
}
// Returns input with 7 zeros padded on the left
echo invoice_num(1); // Output: 0000001
// Returns input with 10 zeros padded
echo invoice_num(1, 10); // Output: 0000000001
// Returns input with prefixed F- along with 7 zeros padded
echo invoice_num(1, 7, "F-"); // Output: F-0000001
// Returns input with prefixed F- along with 10 zeros padded
echo invoice_num(1, 10, "F-"); // Output: F-0000000001
Once you are done writing the helper function, you don't need to use LPAD or CONCAT MySQL functions every time in your query to return ID with padding zeros or zeros with prefix. If you have global access to the helper function in the entire application, you only need to invoke it wherever you want to generate an invoice number.
1 - 0000001 | 0000002 | 0000003 | 0000004 | 0000005
$dbValue = 1;
echo $dbValue = str_pad($dbValue, 7, "0", STR_PAD_LEFT); // it will give 0000001;
2 - F-0000001 | F-0000002 | F-0000003 | F-0000004 | F-0000005
$dbValue = 1;
echo $dbValue = "F-".str_pad($dbValue, 7, "0", STR_PAD_LEFT); // it will produce F-0000001;
Fetch last ID from database and store it in a PHP variable.
For example, if last record is 100, then increment it by 1.
$last = 100; // This is fetched from database
$last++;
$invoice_number = sprintf('%07d', $last);
Finally, the answer for second question is,
$number = "F-". $number;
Ans 1):
You can do this with PHP(directly by concat or use str-pad ) as well as with MySQL( LPAD ) also
But as per my view you should do this by PHP, so that you can change it according to your requirements e.g. extend zeroes as per number of id's in DB.So that not to change SQL queries and make it heavy.
Ans 2):
You can use both formats but if you want to be more specific about particular user or any thing else, then use second format.
I think second format can give you more information about data

different output of same value in different situations - array

I can't understand why these arrays give me different outputs:
• this value 1/4 came from a table (db)
id | value
...
2 | 1/4
3 | 1/7
echo $matrix[0][2]; //show 1/4
• but if i do = 1/4
echo $matrix[0][2] = 1/4 // show 0.25
this occurs in all fractions values. For example 1/7 in first example show 1/7, but in second show 0.142857142
So, my question is why ? I want always decimal value, but the first code as i said, is not working with decimals.
thanks
In the first example, you are retrieving string values from the database. In the second example, you are evaluation a mathematical expression.
Your best bet would be to do something like:
$t = explode("/", $matrix[0][2]);
echo ($t[0] / $t[1]);
The value from the database is a string and the value you set yourself is a float.
If you are using MySQL you can use mysql_fetch_field to know a field type, wich can be usefull when you're working with MyISAM (MySQL always return strings).
You have the easy/ugly solution:
$var = '1/4';
echo (float)eval('return '.$var.';');
An other solution:
$var = '1/4';
$tmp = explode('/', $var, 2);
$tmp = $tmp[0]/$tmp[1];
echo $tmp;
But I think the best solution is to save the result in your database (0.25 for example) and to cast the results into float when you're getting them.
Cos' in the first example value have a string type and in the second you're calculating math function and the answer have a floating point type.
If u'll use this construction "echo $a = '1/4';" the output will be the same.

Categories