php function: number_format() - php

$result = number_format($x, 2, '.', ','); //Will do the following correctly
115255 = 115,225.00
115255.4 = 115,225.40
115255.40 = 115,225.40
115255.455 = 115,255.46
But I need when the user enters more than 2 digits after the decimal, not to cut them into 2 decimals only and to use it as it is...
115255.455 = 115,255.455
115255.4557 = 115,255.4557
Can I do something like that?
if($x == number_format($x, 3)) //I will do it in while loop later, lets test 3 now
$result = number_format($x, 3, '.', ',');
else $result = number_format($x, 2, '.', ',');
The previous if condition never works, else only works

One not traditional way to do this:
$parts = explode(".", $x);
$integerPart = number_format($parts[0], 0, '', ',');
$result = $integerPart.".".$parts[1];

Related

VARCHAR SQL contains numbers how to get 2 decimals after comma

I'm having some trouble getting the price to show correct on my website. Currently i have a row VerkoopPP40 which is a VARCHAR input. In this row there is a price e.g. 89,5 or just 9. When I try to get these values it does some unexpected things.
**** Update ****
I've just tried this code:
<?php
function formatNumber($number, $format=[], $oldDecimalSeparator=",.·'", $multiplier=1)
{
if ($format) {
$format += ['numOfDecimals' => 0, 'decimalSeparator' => '.', 'thousandSeparator' => '']; # Default format
# Find decimal separator
# The decimal separator is the one that is the last and does not occur more than once
if ($letters = str_replace(' ', '', $number)) { # Replace spaces
if ($letters = preg_replace('/^-/', '', $letters)) { # Remove minus
if ($letters = preg_replace('/[0-9]/', '', $letters)) { # Get all non digits
$lastletter = substr($letters, -1); # Returns last char
if (substr_count($letters, $lastletter) == 1) {
if (strpos($oldDecimalSeparator, $lastletter) !== false)
$oldDecimalSep = $lastletter;
else
return $number;
}
}
}
}
$number = preg_replace('/[^0-9-]/', '', $number); # Remove all non digits except 'minus'
if ($oldDecimalSep)
$number = str_replace($oldDecimalSep, '.', $number); # Format to float
if ($multiplier != 1)
$number = $number * $multiplier;
# Convert float to new format
$number = number_format($number,
$format['numOfDecimals'],
$format['decimalSeparator'],
$format['thousandSeparator']
);
}
return $number;
}
This returns: 9,00 and 895,00 so the comma is in a different place right now. It's something I guess... Anyone got an idea to move the comma and remove a 0.
**** End Update ****
And echo-ed it like this:
<td><p>vanaf " . formatNumber($number, [
'numOfDecimals' => 2,
'decimalSeparator' => ',',
'thousandSeparator' => ' '
], ',.') . " p.p. <small>Excl btw</small></p></td>
If I just echo the VerkoopPP40 row it returns: €89,5 or €9.
So I googled around some and found this:
$var = $row["VerkoopPP40"];
$var = ltrim($var, '0');
$foo = $var;
$prijzen = number_format($foo, 2, ',', '');
This turns the . into a ,. But also returns €9,00 for the row that has 9 in it. But the strange thing is the row that has 89.5 in it now just returns €89,00. So somewhere in the code it rounds the numbers down.
Does anyone know how to get the price to show just €9,00 and €89,50 respectively.
I tried the following codes as well:
SELECT ROUND(VerkoopPP40,2) AS RoundedPrice
As database query. That didn't work.
$prijzen = CAST($prijzen as decimal(2,2));
Also didn't work. Any more ideas?
Don't know if this will help you, but found in the comments of the PHP doc : "To prevent the rounding that occurs when next digit after last significant decimal is 5 (mentioned by several people)..." read more
$num1 = "89,5";
$num2 = str_replace(',', '.', $num1);
$price = number_format($num2, 2, '.', '');
echo"[ $price ]";
you should use number_format but in the right way let me explain it to you
you tried this with 89.5
$prijzen = number_format($foo, 2, ',', '');
but this is written for 89,5 not for 89.5
//this will work for you
$var = $row["VerkoopPP40"];
echo 'raw output from database is :'.$var;
$var = $var / 10;
echo 'after this step the number is :'.$var;
$var = number_format($var, 2, '.', '');
echo 'after this step the number is :'.$var;
number_format(the input number, decimal places, 'the divider between whole numbers and decimals', '')

Round numbers in array to 2 decimals

In a array of numbers that have 4 decimals, how can I round them with only 2 decimals? I'm also using a str_replace to replace commas with dots.
foreach($data as $key => $value) {
$vf .= str_replace(",", ".", round($value['vf'])); // gives 1.111, 2.222 etc
$vf .= str_replace(",", ".", round($value['vf'],2)); // does nothing
}
How can I round the values to a number with 2 digits, like 1.11?
You can use number_format.
$n = 12.34567890;
echo number_format($n, 2, '.');
// 12.35
You can even use it to add a thousands separator:
$n = 12345.67890;
echo number_format($n, 2, '.', ',');
// 12,345.68
Or you can use round.
$n = 12.34567890;
echo round($n, 2);
// 12.35

How to split a string into chunks of non-fixed lengths using php?

End goal: Changing chunks of numbers in a database like 0000000 and 22222 and 333333333333 into different lengths. For example, phone numbers that may include prefixes like country codes (e.g. +00 (000) 000-0000, or a pattern of 2, 3, 3, 4), so the option of being able to change the length depending on a different phone number format would be nice.
I love the idea of using explode or chunk_split for the simplicity, as I will be processing a lot of data and I don't want it to drain the server too much:
$string = "1111111111";
$new_nums = chunk_split($string, 3, " ");
echo $new_nums;
^ Only problem here is that I can only use one digit for the length.
What's the best way to go about it? Should I create a function?
Although you mention a phone number in your example it sounds like you wanted something that could do more while also being allowed to specify multiple and variable chunk lengths. One way to do this is to create a function that takes your data, delimiter/separator character and a number of chunk values.
You could make use of func_num_args() and func_get_args() to figure out your chunk lengths.
Here is an example of such a function:
<?php
function chunkData($data, $separator)
{
$rebuilt = "";
$num = func_num_args();
$args = func_get_args();
if($num > 2)
{
for($i = 2; $i < $num; $i++)
{
if(strlen($data) > 0)
{
$string = substr($data, 0, $args[$i]);
$segment = strpos($data, $string);
if($segment !== false)
{
$rebuilt .= $string . $separator;
$data = substr_replace($data, "", 0, $args[$i]);
}
}
}
}
$rebuilt .= $data;
$rebuilt = rtrim($rebuilt, $separator);
return $rebuilt;
}
//Usage examples:
printf("Phone number: %s \n", chunkData("2835552093", "-", 3, 3, 4));
printf("Groups of three letters: %s \n", chunkData("ABCDEFGHI", " ", 3, 3, 3));
printf("King Roland's passcode: %s \n", chunkData("12345", ",", 1, 1, 1, 1, 1));
printf("Append leftovers: %s \n", chunkData("BlahBlahBlahJustPlainBlah", " ", 4, 4, 4));
printf("Doesn't do much: %s \n", chunkData("huh?", "-"));
?>
//Output:
Phone number: 283-555-2093
Groups of three letters: ABC DEF GHI
King Roland's passcode: 1,2,3,4,5
Append leftovers: Blah Blah Blah JustPlainBlah
Doesn't do much: huh?
With regex?
$regex = "/(\\d{2})(\\d{3})(\\d{3})(\\d{4})/";
$number = "111111111111";
$replacement = "+$1 ($2) $3-$4";
$result = preg_replace($regex, $replacement, $number);
https://regex101.com/r/gS1uC1/1

How to increment a default value in mysql

I have a field (demo_field)(varchar) in mysql table. I want to increment this field value with a pre defined prefix.
For example my field first value is demo001. Now when ever new values inserted I want to increment the numeric numbers like demo002, demo003.
How can I do this with PHP.
try this -
//fetch data from table
$sql = $mysqli->query('select count(demo_field) as total,demo_field from tablename limit 1');
$res = $sql->fetch_assoc();
//generate string from existing data
$str = substr($res['demo_field'], 0, 4);
$dig = str_replace($str, '', $res['demo_field']);
$dig = $dig+$res['total'];
//add padding if needed
$dig = str_pad($dig, 3, '0', STR_PAD_LEFT);
//concatenate string & digits
$newStr = $str.$dig;
var_dump($newStr);
Another way without count
$sql = $mysqli->query('select max(demo_field) as demo_field from demo');
$res = $sql->fetch_assoc();
$str = substr($res['demo_field'], 0, 4);
$dig = str_replace($str, '', $res['demo_field']);
$dig += 1;
$dig = str_pad($dig, 3, '0', STR_PAD_LEFT);
$newStr = $str.$dig;
var_dump($newStr);
hope this might solve the problem with count.
another solution with max count for alphanumeric string and without padding -
$sql = $mysqli->query('select max(cast(substring(demo_field, 5) as unsigned)) as digit, demo_field from demo');
$res = $sql->fetch_assoc();
$str = substr($res['demo_field'], 0, 4);
$dig = $res['digit'] + 1;
$newStr = $str.$dig;
var_dump($newStr);
//use PHP not mysql
$pre = 'demo';
$num = 0;
define('MAX', 100);
for($num = 0; $num < MAX; $num++)
{
$pre_str = $pre . sprintf("%03d", $num);
//insert here
}
you have to use an INT field
and translate it to whatever format you want at "select" time.
In MySQL we cannot use AutoIncrement for Varchar.

Show decimal point number in PHP

I hold decimals in a database using DECIMAL(10,5)
I would like to format these numbers according to a few rules:
A zero decimal should display as 0
Show a long decimal (no trailing zero's) with all of it's numbers
When possible, I would like to only show up to 2 decimal places (when there are trailing zeros)
Here are some examples:
The left side corresponds to how the number is stored in database.
The right number is how I would like to display the number in my application.
0.00000 => 0
0.51231 => 0.51231
0.12000 => 0.12
0.40000 => 0.40
0.67800 => 0.678
12.10000 => 12.10
This will work for you:
function format($x){
if(!(int)substr_replace($x, '', $dpos = strpos($x, '.'), 1))
return 0;
else
return str_pad((rtrim($x, '0')), $dpos + 3, '0');
}
Example
I would utilize the number_format function in php to actually do the formatting after you determine the amount of decimal places to the number has.
Source:
http://php.net/manual/en/function.number-format.php
Example Usage:
$number = 1234.56;
// english notation (default)
$english_format_number = number_format($number);
// 1,235
// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56
$number = 1234.5678;
// english notation without thousands separator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57
Well here's one way (I haven't tested it yet so there may be minor errors):
$pattern = '/([0-9]+)\\.{0,1}([0-9]*?)0*$/';
$subject = 12.10000;
$matches = array();
$result = preg_match ($pattern, $subject, $matches);
$number = $matches[1];
if ($matches[2] != 0) {
$number .= '.'.$matches[2];
if ($matches[2] < 10) {
$number .= '0';
}
}
echo $number;
And here's another way (probably a little faster):
$x = 1.000;
$result = (int)$x;
$trimmed = rtrim($x, 0);
if ($trimmed[strlen($trimmed) - 1] != '.') {
if ($trimmed[strlen($trimmed) - 2] == '.') {
$result = $trimmed.'0';
} else {
$result = $trimmed;
}
}
echo $result;
I haven't used it myself, but theres the NumberFormatter class: http://php.net/manual/class.numberformatter.php as part of the Internationalization Functions for this stuff. Using that is a little more involved i think though.
I know this is an old question, but the following quick function I wrote for my own project might help someone looking for this.
function number_format_least_dp($number, $decimal_point = '.', $thousand_seperator = ','){
if (floatval($number) == (int)$number){
$number = number_format($number, 0, $decimal_point, $thousand_seperator);
} else {
$number = rtrim($number, '.0');
$number = number_format($number, strlen(substr(strrchr($number, '.'), 1)), $decimal_point, $thousand_seperator);
}
return $number;
}

Categories