Add commas as thousands separator and floating point dot in php - php

I have this
$example = "1234567"
$subtotal = number_format($example, 2, '.', '');
the return of $subtotal is "1234567.00"
how to modify the definition of $subtotal, make it like this "1,234,567.00"

Below will output 1,234,567.00
$example = "1234567";
$subtotal = number_format($example, 2, '.', ',');
echo $subtotal;
Syntax
string number_format ( float $number , int $decimals = 0 , string $dec_point = '.' , string $thousands_sep = ',' )
But I advise you to use money_format which will formats a number as a currency string

You have many options, but money_format can do the trick for you.
// Example:
$amount = '100000';
setlocale(LC_MONETARY, 'en_IN');
$amount = money_format('%!i', $amount);
echo $amount;
// Output:
"1,00,000.00"
Please note that money_format() is only defined if the system has strfmon capabilities. For example, Windows does not, so it is undefined in Windows.
Final edit: Here's a pure PHP Implementation that will work on any system:
$amount = '10000034000';
$amount = moneyFormatIndia( $amount );
echo number_format($amount, 2, '.', '');
function moneyFormatIndia($num){
$explrestunits = "" ;
if(strlen($num)>3){
$lastthree = substr($num, strlen($num)-3, strlen($num));
$restunits = substr($num, 0, strlen($num)-3); // extracts the last three digits
$restunits = (strlen($restunits)%2 == 1)?"0".$restunits:$restunits; // explodes the remaining digits in 2's formats, adds a zero in the beginning to maintain the 2's grouping.
$expunit = str_split($restunits, 2);
for($i=0; $i<sizeof($expunit); $i++){
// creates each of the 2's group and adds a comma to the end
if($i==0){
$explrestunits .= (int)$expunit[$i].","; // if is first value , convert into integer
}else{
$explrestunits .= $expunit[$i].",";
}
}
$thecash = $explrestunits.$lastthree;
} else {
$thecash = $num;
}
return $thecash; // writes the final format where $currency is the currency symbol.
}

Ref: http://php.net/manual/en/function.money-format.php
string money_format ( string $format , float $number )
ex:
// let's print the international format for the en_US locale
setlocale(LC_MONETARY, 'en_US');
echo money_format('%i', $number) . "\n";
// USD 1,234.56
Note: The function money_format() is only defined if the system has strfmon capabilities. For example, Windows does not, so money_format() is undefined in Windows.
Note: The LC_MONETARY category of the locale settings, affects the behavior of this function. Use setlocale() to set to the appropriate default locale before using this function.
Use number_format : http://www.php.net/manual/en/function.number-format.php
string number_format ( float $number , int $decimals = 0 , string $dec_point = '.' , string $thousands_sep = ',' )
$number = 123457;
$format_number = number_format($number, 2, '.', ',');
// 1,234.57

Related

PHP Decimal128 string formating

I am using MongoDB to store values as Decimal128 and using PHP with Twig to display them. My question is there a format the output with a thousands separator? I have tried using number_format, but that doesn't work because the value is a string not a int or float. I don't want to type cast the value because I want the value to be precision.
Examples:
1000.382 = 1,000.382
99.01 = 99.01
1900000 = 1,900,000
I wrote a function to do this. Still wondering if there is a better way to do it.
<?php
$n = '12345.001';
echo fNumString($n);
function fNumString ($number_string) {
$ex_num = explode('.', $number_string);
$whole_num_len = strlen($ex_num[0]);
$formated = '';
if ($whole_num_len > 3) {
for ($i = 0; $i < $whole_num_len; $i++) {
$formated .= $ex_num[0][$i];
if ((($whole_num_len - ($i + 1)) % 3) == 0 && $whole_num_len != ($i + 1))
$formated .= ',';
}
} else
$formated = $ex_num[0];
if (count($ex_num) == 2)
$formated .= '.' . $ex_num[1];
return $formated;
}
You could:
split the number string into integer and decimal parts using explode,
reverse the integer part using strrev,
add a thousands separator every 3 digits within that integer part using preg_replace,
reverse the integer part back using strrev,
return it concatenated with the decimal separator and the decimal part
Code:
function fNumString(string $numberString, string $decimalPoint = '.', string $thousandsSeparator = ','): string
{
[$integerPart, $decimalPart] = array_pad(explode('.', $numberString, 2), 2, null);
$integerPart = strrev(preg_replace('/\d{3}(?=\d)/', '\0' . $thousandsSeparator, strrev($integerPart)));
return $integerPart . ($decimalPart ? $decimalPoint . $decimalPart : '');
}
Demo: https://3v4l.org/m3jUC
Note: you could leave out the last 2 parameters of number_format, I like keeping them out for clarity (and in case they change the default values later for some reason).

Modify decimal point and thousands separator without changing the number of decimals

I'm new to php and I'm trying to use number_format :
number_format ( float $number , int $decimals = 0 , string $dec_point = "." , string $thousands_sep = "," )
As in the title, my goal is to modify decimal point and thousands separator without changing the number of decimals as below:
$Num=123456.789;
$Num2=number_format ($Num, [decimals as in $Num], ",", "'" );
My result should be:
$Num2="123'456,789";
Edit
I need a code for an unknown number of decimals
You can use NumberFormatter.
You will still need to specify a certain amount of fraction digits, but you can just use a high enough value and be fine. It's not like the number of digits is really arbitrary. It's tied to your precision ini setting.
$formatter = new NumberFormatter("en_US", NumberFormatter::DECIMAL);
$formatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, 42);
$formatter->setSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL, "'");
$formatter->setSymbol(NumberFormatter::DECIMAL_SEPARATOR_SYMBOL, ",");
echo $formatter->format(123456.7891234); // 123'456,7891234
Demo https://3v4l.org/TCAIA
You can do it such a way (firstly take a look to #Gordon answer – it's much more better):
<?php
function extendedNumberFormat($num, $decimalSeparator, $thousandSeparator) {
$asStr = strval($num);
$exploded = explode('.', $asStr);
$int = $exploded[0];
$decimal = isset($exploded[1]) ? $exploded[1] : null;
$result = number_format($int, 0, ".", $thousandSeparator);
if ($decimal !== null) {
$result .= $decimalSeparator . $decimal;
}
return $result;
}
echo extendedNumberFormat(123456.789, ',', "'") . "\n";
echo extendedNumberFormat(123456.7891, ',', "'") . "\n";
echo extendedNumberFormat(123456, ',', "'") . "\n";
//123'456,789
//123'456,7891
//123'456

PHP number format with integer format

I am using PHP number_format to express prices of products, using decimal point, thousands separators, etc. For example:
$price = 20.456;
print "$" . number_format($price, 2, ".", ",");
outputs $20.46.
However, I would like that, if the price is integer, for example $price = 20.00, to output $20. Is there some other function or rule to achieve this, avoiding decimal points if not necessary?
Just do a loose comparison of $price cast as integer against $price, if they match (ie. it's a whole number), you can format to 0 decimal places:
number_format($price, ((int) $price == $price ? 0 : 2), '.', ',');
You can use ternary operator fot that:
$price = 20.456;
print "$" . ($price == intval($price) ? number_format($price, 0, "", ",") : number_format($price, 2, "", ","));
Try $price = 20.456 +0 ;
$price + 0 does the trick.
echo 125.00 + 0; // 125
echo '125.00' + 0; // 125
echo 966.70 + 0; // 966.7
Internally, this is equivalent to casting to float with (float)$price or floatval( $price) but I find it simpler.
A little helper function my_format to determine if the number is an integer and then return the corresponding string.
function my_format($number)
{
if (fmod($number, 1) == 0) {
return sprintf("$%d\n", $number);
} else {
return sprintf("$%.2f\n", $number);
}
}
$price = 20.456;
echo my_format($price);
echo my_format(20);
Will output
$20.46 $20
A little solution that works for any number
$price = "20.5498";
$dec = fmod($price, 1);
if($dec > 0)
print "$" . number_format($price, 2, ".", ",");
else
print "$" . floor($price);;
You can use floor() function
$price = 20.456;
echo '$'.floor($price); // output $20

convert scientific notation to decimal with php

math with bitcoin is giving me problems
$value = bcmul((float)$TotalMoney, $p,8);
$value = bcdiv((float)$Value, 100,8);
returns 8.431e-05 as one of the values in the script
i've tried
$newNum = (float)$value;
$newNum = number_format((float)$value, 8);
$newNum = sprintf('%.8f',$value);
function scientific_notation($in_float_value, $in_decimal_place_count = -1)
{
// Get the exponent
$abs_float_value = abs($in_float_value);
$exponent = floor($abs_float_value == 0 ? 0 : log10($abs_float_value));
// Scale to get the mantissa
$in_float_value *= pow(10, -$exponent);
// Create the format string based
// on the requested number of decimal places.
$format = ($in_decimal_place_count >= 0) ? "." . $in_decimal_place_count : "";
//echo("Format0: $format");
// Format the exponent part using zero padding.
$formatted_exponent = "+" . sprintf("%02d", $exponent);
if($exponent < 0.0)
{
$formatted_exponent = "-" . sprintf("%02d", -$exponent);
}
$format = "%" . $format . "fe%s";
//echo("Format1: $format");
// Return the final value combining mantissa and exponent
return sprintf($format, $in_float_value, $exponent);
}
$newNum = scientific_notation($value,8);
Tried it in phpfiddle and it works. maybe the problem is storing it in a db. It's stores as 8.431e-05 in the database
what am I doing wrong?
Use the exemple below to convert Scientific Notation to float/decimal on PHP:
echo sprintf('%f', floatval('-1.0E-5'));//default 6 decimal places
echo sprintf('%.8f', floatval('-1.0E-5'));//force 8 decimal places
echo rtrim(sprintf('%f',floatval(-1.0E-5)),'0');//remove trailing zeros
When working with Bitcoin balances it is recommended to store amounts in a database in satoshis as an integer and then you can convert it back to 8 decimals when displaying it on the screen to users.
$amount = 0.0132;
$convert = $amount * 100000000;
// store in DB as the converted amount 1320000 as an integer
// when grabbing from DB convert it back
$databaseValue = 1320000;
$convertBack = $databaseValue / 100000000;
$display = number_format($convertBack, 8);
echo $display;

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