PHP Format Number For Display and Insert to DB - php

I'm retrieving values from MySQL numeric field and want to format with a comma separator for 1000s like this: 21,000
This code below seems to work for display - how do I strip out the commas again before updating and inserting into MySQL DB?
<input type="text" name="Price id="Price value="<?php echo number_format($row_['Price'])); ?>" size="10" />
Thanks .........

You can use the numberFormatter class for both making and stripping the formatting around values quite nicely:
You can format easily with format()
<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
$data = numfmt_format($fmt, 1234567.891234567890000);
if(intl_is_failure(numfmt_format($fmt))) {
report_error("Formatter error");
}
?>
Output
1.234.567,891
Then, the parse() function will let you remove whatever formatting you applied to get back to your original format.
<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
$num = "1.234.567,891";
echo numfmt_parse($fmt, $num)."\n";
echo numfmt_parse($fmt, $num, NumberFormatter::TYPE_INT32)."\n";
?>
Output:
1234567.891
Note: Keep in mind that if you are passing these things in forms and back and forth, you will potentially lose decimal places or the like if you format them down.

Not sure I understood your question correctly, but you could remove the character with str_replace...
str_replace(",", "", $Price);

Related

How to format "datetime -local" value in php fetched from mysql?

I have an input field in html where I want to echo the value of datetime stored in mysql.
<input type="datetime -local" name="schedule" value="<?php echo $result['schedule']; ?>
But despite the value being there in mysql db as YY/mm/dd h:m:s the value is not showing up. What could be the possible issue? When I try to echo outside the input value it displays the result. My thoughts are that the datetime needs formatting according to the html datetime -local input field.
Please suggest me any way if possible.
T is a format character(Timezone abbreviation e.g: EST, MDT…) so you can't use it directly. Escape it (\T) to get a literal T character:
datetime.format.php
You can prevent a recognized character in the format string from being expanded by escaping it with a preceding backslash.
<?php
$date = date("Y-m-d\TH:i:s", strtotime($result['schedule']));
?>
<input type="datetime-local" name="schedule" value="<?php echo $date; ?>"/>
use <?=$date?> instead of <?php echo $date; ?>
You are filling it the wrong way. Read the documentation about the input-type datetime-local The correct format is YYYY-MM-DDTHH:MM - note the T as divider between date and time.
Also:
you wrote the type wrong. Correct is datetime-local
you are missing the closing quote at the value attribute.
This is how to fix it
<input type="datetime-local" name="schedule" value="<?php echo $date = date("Y-m-d\TH:i:s", strtotime($result['schedule']));?>">

How to "cut the fluff" out from PHP's NumberFormatter to display a "compact" money sum for a spreadsheet context? [duplicate]

I'm trying to format revenue totals as grabbed from a db, and using php's NumberFormatter class, with the formatCurrency method.
However, I do not want to print out the actual € / Euro symbol with this. I just want the plain number, with comma's and decimal points.
Example;
1234.56 should be formatted as 1,234.56
The current output is giving €1,234.56.
Code I'm using:
$array['total_revenue'] = $this
->db
->query($sql)
->row_array()['SUM( booking_total )'];
$formatter = new NumberFormatter('en_GB', NumberFormatter::CURRENCY);
echo $formatter->formatCurrency($array['total_revenue'], 'EUR') . PHP_EOL;
Would anyone have any ideas on how I can fix this up to remove the euro symbol?
You should use setSymbol() function:
$formatter = new NumberFormatter('en_GB', NumberFormatter::CURRENCY);
$formatter->setSymbol(NumberFormatter::CURRENCY_SYMBOL, '');
echo $formatter->formatCurrency($array['total_revenue'], 'EUR') . PHP_EOL;
I came here because for some reason, $formatter->setSymbol(NumberFormatter::CURRENCY_SYMBOL, ''); was being ignored by $formatter->formatCurrency($array['total_revenue'], 'USD');
To resolve this issue, I found out a solution here.
https://www.php.net/manual/en/numberformatter.setsymbol.php#124153
this could be obvious to some, but setSymbol(NumberFormatter::CURRENCY_SYMBOL, '') doesn't work for formatCurrency - it will simply be ignored...
use NumberFormatter::CURRENCY and $fmt->format(123); to get a currency value with the symbol specified as CURRENCY_SYMBOL (or INTL_CURRENCY_SYMBOL)
i.e
$fmt = new NumberFormatter('de_DE', NumberFormatter::CURRENCY);
$fmt->setSymbol(NumberFormatter::CURRENCY_SYMBOL, '');
$fmt->setAttribute(NumberFormatter::FRACTION_DIGITS, 2);
echo $fmt->format(56868993064.7985);
//Output: 56.868.993.064,80 
A simple regex is a quick fix for your problem. Try;
$actual = $formatter->formatCurrency($array['total_revenue'], 'EUR') . PHP_EOL;
$output = preg_replace( '/[^0-9,"."]/', '', $actual );
echo $output;
Hope this helps
The formatCurrency() method is convenient in that it automatically formats the amount according to the rules of the specified currency. For example, when formatting an amount in Euros, the number should show 2 decimal places. But when formatting an amount in Yen, the number should have no decimals as fractions of Yen do not exist (as far as I know). Other currencies may have 3 or even 4 decimals.
If the goal is to keep all functionality of the formatCurrency() method except for the removal of the currency symbol (or code), then I'd suggest this snippet:
$localeCode = 'en_US';
$currencyCode = 'USD';
$amount = 10000;
$formatter = new \NumberFormatter($localeCode, \NumberFormatter::CURRENCY);
$formatter->setTextAttribute(\NumberFormatter::CURRENCY_CODE, $currencyCode);
$formatter->setSymbol(\NumberFormatter::CURRENCY_SYMBOL, '');
$formatter->format($amount);
Please note that it is necessary to set the currency code BEFORE clearing the currency symbol. Trying to set the currency after clearing the symbol will not work, as setting the currency will automatically load the related symbol.

Removing currency symbol from formatCurrency

I'm trying to format revenue totals as grabbed from a db, and using php's NumberFormatter class, with the formatCurrency method.
However, I do not want to print out the actual € / Euro symbol with this. I just want the plain number, with comma's and decimal points.
Example;
1234.56 should be formatted as 1,234.56
The current output is giving €1,234.56.
Code I'm using:
$array['total_revenue'] = $this
->db
->query($sql)
->row_array()['SUM( booking_total )'];
$formatter = new NumberFormatter('en_GB', NumberFormatter::CURRENCY);
echo $formatter->formatCurrency($array['total_revenue'], 'EUR') . PHP_EOL;
Would anyone have any ideas on how I can fix this up to remove the euro symbol?
You should use setSymbol() function:
$formatter = new NumberFormatter('en_GB', NumberFormatter::CURRENCY);
$formatter->setSymbol(NumberFormatter::CURRENCY_SYMBOL, '');
echo $formatter->formatCurrency($array['total_revenue'], 'EUR') . PHP_EOL;
I came here because for some reason, $formatter->setSymbol(NumberFormatter::CURRENCY_SYMBOL, ''); was being ignored by $formatter->formatCurrency($array['total_revenue'], 'USD');
To resolve this issue, I found out a solution here.
https://www.php.net/manual/en/numberformatter.setsymbol.php#124153
this could be obvious to some, but setSymbol(NumberFormatter::CURRENCY_SYMBOL, '') doesn't work for formatCurrency - it will simply be ignored...
use NumberFormatter::CURRENCY and $fmt->format(123); to get a currency value with the symbol specified as CURRENCY_SYMBOL (or INTL_CURRENCY_SYMBOL)
i.e
$fmt = new NumberFormatter('de_DE', NumberFormatter::CURRENCY);
$fmt->setSymbol(NumberFormatter::CURRENCY_SYMBOL, '');
$fmt->setAttribute(NumberFormatter::FRACTION_DIGITS, 2);
echo $fmt->format(56868993064.7985);
//Output: 56.868.993.064,80 
A simple regex is a quick fix for your problem. Try;
$actual = $formatter->formatCurrency($array['total_revenue'], 'EUR') . PHP_EOL;
$output = preg_replace( '/[^0-9,"."]/', '', $actual );
echo $output;
Hope this helps
The formatCurrency() method is convenient in that it automatically formats the amount according to the rules of the specified currency. For example, when formatting an amount in Euros, the number should show 2 decimal places. But when formatting an amount in Yen, the number should have no decimals as fractions of Yen do not exist (as far as I know). Other currencies may have 3 or even 4 decimals.
If the goal is to keep all functionality of the formatCurrency() method except for the removal of the currency symbol (or code), then I'd suggest this snippet:
$localeCode = 'en_US';
$currencyCode = 'USD';
$amount = 10000;
$formatter = new \NumberFormatter($localeCode, \NumberFormatter::CURRENCY);
$formatter->setTextAttribute(\NumberFormatter::CURRENCY_CODE, $currencyCode);
$formatter->setSymbol(\NumberFormatter::CURRENCY_SYMBOL, '');
$formatter->format($amount);
Please note that it is necessary to set the currency code BEFORE clearing the currency symbol. Trying to set the currency after clearing the symbol will not work, as setting the currency will automatically load the related symbol.

PHP preg_filter returns unexpected long value

Trying to strip tags and filter value in Woocommerce but can't manage o get it in the correct format. Something is fishy..
Am using WC()->cart->get_cart_subtotal(); to retrieve the value. In this example my value is 2,429kr and the raw returned value is <span class="amount">2,429kr</span>
$cart_total = WC()->cart->get_cart_subtotal();
$cart_total_format = strip_tags($cart_total);
$cart_value = preg_filter("/[^0-9,.]/", "", $cart_total_format);
echo $cart_value;
Result = 2,429107114
Expected = 2,429
Am not a PHP wizard so i thought i was doing something wrong and did try several diffren't approches and methods without getting the correct result.
Then i did try to run the raw out output from WC()->cart->get_cart_subtotal(); as a $string
$string_total = '<span class="amount">2,429kr</span>';
$string_total_format = strip_tags($string_total);
$string_value = preg_filter("/[^0-9,.]/", "", $string_total_format);
echo $string_value;
Result = 2,429
Expected = 2,429
Why? :(
Update
Found this when digging around in Woocommerce #Github
case 'SEK' : $currency_symbol = 'kr'; break;
So the real value is:
<span class="amount">2,429kr</span>
Question now is what the best approach to filter this out ? My quick fix approach is this, it's not beautiful but fix the issue.
$cart_total = WC()->cart->get_cart_subtotal();
$cart_total_format = strip_tags($cart_total);
$cart_value = preg_filter("/[^0-9,.]/","", $cart_total_format);
$cart_value_new = preg_filter("/107114/",".", $cart_value);
echo $cart_value_new;
Result = 2,429
Expected = 2,429
Ok, so this is what is happening. get_cart_subtotal() returns an HTML-encoded string. Because you are not looking at the actual source, but rather var_dump-ing it and looking at the HTML you are seeing <span class="amount">2,429kr</span>, when in fact the "k" and "r" are encoded into their equivalent HTML entities (based on their ASCII codes), k and &#114.
That is also why var_dump shows string(45) "2,429kr" when it should in fact return string(7) "2,429kr" if the currency weren't encoded (and the <span> tags weren't interpreted by the browser).
Then, when you apply the preg_filter, it also includes the numbers from the HTML entities, of course, because they match the regular expression.
So the easiest solution is to decode all HTML entities before filtering:
$cart_total = html_entity_decode($cart_total, ENT_QUOTES, 'UTF-8');
so your code becomes:
$cart_total = WC()->cart->get_cart_subtotal();
$cart_total = html_entity_decode($cart_total, ENT_QUOTES, 'UTF-8');
// rest of your code
Just a guess:
Maybe WC()->cart->get_cart_subtotal() return '<span class="amount">2,429107114kr</span>', but when you display it you see <span class="amount">2,429kr</span> because of some javascript that round it.

PHP textarea into database

I'm using textarea to get data that I insert into a database.
I'm using htmlspecialchars() to get rid of the single quotes and double quotes but it doesn't convert new lines into something so I'm left with a very long piece of code that doesn't have new lines and looks messy.
I've checked the manual but I can't find how to convert it.
How would I do this?
EDIT:
My intended output is the same as what the user inputted.
So if they inputted into the textarea...
Hi
This is another line
This is another line
It would store into the database like...
Hi\r\nThis is another line\r\n This is another line.
or something like that.
Then when I echo it again then it should be fine.
Anthony,
If you are referring to when you get it back out and you want it to look nice, and you aren't putting it back into a textarea, you can use the mythical function nl2br() to convert new line characters into HTML characters.
$data = 'Testing\r\nThis\r\nagain!\r\n';
echo nl2br($data);
This results in:
Testing
This
again!
I believe what you are looking for is
nl2br($string);
That will convert the returns to <br> tags
I will also give you this script that has worked well for me in the past when nl2br does not.
$remove = array("\r\n", "\n", "\r", "chr(13)", "\t", "\0", "\x0B");
$string = str_replace($order, "<br />", $string);
It should be:
<?php
addslashes( strip_tags( nl2br( $data ) ) );
?>
addslashes : will escape quotes to prevent sql injection
strip_tags : will remove any html tags if any
nl2br : will convert newline into <br />

Categories