I'm looking for a way to use the php number_format function or something similar that will add the thousand seperator but will leave any decimal part of the number intatct without and formatting of this. For example:
39845.25843 => 39,845.25843
347346.8 => 347,346.8
1000000 = > 1,000,000
Thanks
$val = number_format($val, strlen(end(explode('.', $val))));
Edit: if you want to handle integers also the above won't work without adding a case for no decimal
$val = number_format( $val, (strstr($val, '.')) ? strlen(end(explode('.', $val))) : 0 );
I'm with little imagination for variable names, but this will do:
function conv($str) {
$t = explode(".", $str);
$ret = number_format(reset($t), 0);
if (($h = next($t)) !== FALSE)
$ret .= "." . $h;
return $ret;
}
same as above but my twist:
function mod_numberformat($num){
// find & cache decimal part
$pos = strpos($num, '.');
$decimal = $pos !== false ? substr($num, $pos) : '';
// format number & avoid rounding
$number = number_format($num, 9);
// strip new decimal part & concatenate cached part
$number = substr($number, 0, strpos($number, '.'));
$number .= $decimal;
return $number;
}
Related
This question already has answers here:
php - add comma thousands separator but remove trailing zeros
(4 answers)
Closed 5 years ago.
A while ago I wrote a fully working script to magically move the decimal sign, adapted to the number of zeros there are.
https://github.com/jenstornell/magic-number-format/blob/master/magic-number-format.php
I still wonder, is there a PHP function to cover this issue? I feel like my code is just too much:
<?php
function magic_number_format($number) {
$pos = strpos($number, '.');
$pos = ( ! $pos ) ? strpos($number, ',') : $pos;
if( $pos ) {
$count = strlen($number) - $pos - 1;
$last = substr($number, -$count);
$split = str_split($last);
$split = array_reverse($split);
$break = false;
foreach( $split as $char ) {
if( $char == 0 && $break == false ) {
$count--;
}
if( $char != 0 ) {
$break = true;
}
}
$first = number_format( substr($number, 0, $pos ), 0, '', '.' );
$last = substr($number, $pos + 1, $count);
$result = $first . ',' . $last;
$result = ( ! is_numeric( substr($result, -1) ) ) ? substr($result, 0, -1) : $result;
return $result . "\n";
}
return number_format( $number, 0, '', '.' ) . "\n";
}
echo magic_number_format('25');
echo magic_number_format('123.32');
echo magic_number_format('12312.3233');
echo magic_number_format('12.0100000');
echo magic_number_format('1231,00');
echo magic_number_format('1231,10');
echo magic_number_format('1,1');
The code above will skip the unneeded zeros after the comma or dot sign.
You are reinventing the wheel. Also the code in answer linked as duplicate is not necessary neither the only approach nor the best approach (it also is not necessary fully related to your question). You can successfully stick using plain printf() with ordinary %s formatting for expected results. Test case:
$vals = [ 1, 1.000, 1.1, 1.230 ];
foreach ($vals as $val) {
printf("%s\n", $val);
}
would produce desired:
1
1
1.1
1.23
Replace printf) with sprintf() if you need to assing formatted value to a variable and you are good to go.
How can I add a period after the first three characters and then a ' every 3 characters after?
Example
$number = 1100000
Output = 1'100.000
Example2
$number = 560000
Output = 560.000
Example3
$number = 1000256000
Output = 1'000'256.000
I tried number_format but it will add the same symbol (. , ')...thanks!!
$number = 1100000;
$english_format_number = number_format($number, 0, '.', "'");
Output: 1'100'000
$number = 1100000;
$english_format_number = number_format($number, 3, '.', "'");
Output: 1'100'000.000
$number = 1100000;
echo chunk_split($number,1,".");
Thanks!!
You were on the right track with number_format but you have to specify all 4 parameters to achieve the result you are looking for. You also need to divide the number by 1000 to avoid the extra decimal places.
echo number_format($number / 1000, 3, "." , "'");
See: http://php.net/manual/en/function.number-format.php
PHPFiddle: http://phpfiddle.org/main/code/e2c-a6q
I had to do something similar recently, try this function:
function formatMoney($number, $fractional=false) {
if ($fractional) {
$number = sprintf('%.2f', $number);
}
while (true) {
$replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1,$2', $number);
if ($replaced != $number) {
$number = $replaced;
} else {
break;
}
}
return $number;
}
edit for your use
how can i convert it into float and then increment it and then convert back to string.
if($set==$Data_Id)
{
$rel='1.1.1.2';
}
after increment it should be like 1.1.1.3.
Please any help.
so crazy, it may work
$rel='1.1.1.2';
echo substr($rel, 0, -1). (substr($rel,-1)+1); //1.1.1.3
the big question is what do you want to happen if the string ends in 9 ??
Here's a slightly different approach.
<?php
function increment_revision($version) {
return preg_replace_callback('~[0-9]+$~', function($match) {
return ++$match[0];
}, $version);
}
echo increment_revision('1.2.3.4'); //1.2.3.5
Anthony.
"1.1.1.2" is not a valid number. So you'll have to do something like this:
$rel = '1.1.1.2';
$relPlusOne = increment($rel);
function increment($number) {
$parts = explode('.', $number);
$parts[count($parts) - 1]++;
return implode('.', $parts);
}
If this is exactly the case you need to solve, you could do it with intval(), strval(), str_replace(), substr() and strlen().
$rel = '1.1.1.2'; // '1.1.1.2'
// replace dots with empty strings
$rel = str_replace('.', '', $rel); // '1112'
// get the integer value
$num = intval($rel); // 1112
// add 1
$num += 1; // 1113
// convert it back to a string
$str = strval($num); // '1113'
// initialize the return value
$ret = '';
// for each letter in $str
for ($i=0; $i<strlen($str); $i++) {
echo "Current ret: $ret<br>";
$ret .= $str[$i] . '.'; // append the current letter, then append a dot
}
$ret = substr($ret, 0, -1); // remove the last dot
echo "Incremented value: " . $ret;
This method will change 1.1.1.9 to 1.1.2.0, however. If that's what you want, then this will be fine.
I am working on something where I need to generate the sequence 1,2,3...a,b,c,d...z,11,12,13...aa,ab,ac...zzzzzzzz, using php. This will only ever have to happen once, so it dosen't need to be very fast.
Thanks!
function incrementAlphanumeric($number) {
return base_convert(base_convert($number, 36, 10) + 1, 10, 36);
}
echo incrementAlphanumeric(9); // outputs "a"
To populate an array:
$number = 1;
$numbers = array();
while ($number != 'zzzzzzzz') {
$numbers[] = $number;
$number = incrementAlphanumeric($number);
}
http://php.net/base-convert
I recently had to do this with a non-standard set of character (they left out certain characters).
I put together a few functions I found on the net and got:
// this array misses a few letters due to the special naming convention
private $alphabet = array('0', '1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z');
private function createDecimalFromCode($string){
$decimal = 0;
$base = count($this->alphabet);
$charset = implode($this->alphabet, '');
$charset = substr($charset, 0, $base);
do {
$char = substr($string, 0, 1);
$string = substr($string, 1);
$pos = strpos($charset, $char);
if ($pos === false) {
$error[] = "Illegal character ($char) in INPUT string";
return false;
} // if
$decimal = ($decimal * $base) + $pos;
} while($string <> null);
return $decimal;
}
private function createCodeFromDecimal($decimal){
$s = '';
while($decimal > 0) {
$s = $this->alphabet[$decimal%sizeof($this->alphabet)] . $s;
$decimal = floor($decimal/sizeof($this->alphabet));
}
return $s == '' ? '0' : $s;
}
Essentially I take my last created code, convert it to a decimal, add 1 and then convert that back to the next alphanumeric code.
I would like to know how can I add comma's to numbers. To make my question simple.
I would like to change this:
1210 views
To:
1,210 views
and :
14301
to
14,301
and so on for larger numbers. Is it possible with a php function?
from the php manual http://php.net/manual/en/function.number-format.php
I'm assuming you want the english format.
<?php
$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 with a decimal point and without thousands seperator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57
?>
my 2 cents
The Following code is working for me, may be this is helpful to you.
$number = 1234.56;
echo number_format($number, 2, '.', ',');
//1,234.56
$number = 1234.56;
//Vietnam notation(comma for decimal point, dot for thousand separator)
$number_format_vietnam = number_format($number, 2, ',', '.');
//1.234,56
This is a bangladeshi format
First create a function
function numberFormat($number, $decimals=0)
{
// $number = 555;
// $decimals=0;
// $number = 555.000;
// $number = 555.123456;
if (strpos($number,'.')!=null)
{
$decimalNumbers = substr($number, strpos($number,'.'));
$decimalNumbers = substr($decimalNumbers, 1, $decimals);
}
else
{
$decimalNumbers = 0;
for ($i = 2; $i <=$decimals ; $i++)
{
$decimalNumbers = $decimalNumbers.'0';
}
}
// return $decimalNumbers;
$number = (int) $number;
// reverse
$number = strrev($number);
$n = '';
$stringlength = strlen($number);
for ($i = 0; $i < $stringlength; $i++)
{
if ($i%2==0 && $i!=$stringlength-1 && $i>1)
{
$n = $n.$number[$i].',';
}
else
{
$n = $n.$number[$i];
}
}
$number = $n;
// reverse
$number = strrev($number);
($decimals!=0)? $number=$number.'.'.$decimalNumbers : $number ;
return $number;
}
Call the function
* numberFormat(5000000, 2) // 50,00,000.00
* numberFormat(5000000) // 50,00,000
Often, if a number is big enough to have commas in it, you might want to do without any numbers after a decimal point - but if the value you are showing could ever be small, you would want to show those decimal places. Apply number_format conditionally, and you can use it to both add your commas and clip off any irrelevant post-point decimals.
if($measurement1 > 999) {
//Adds commas in thousands and drops anything after the decimal point
$measurement1 = number_format($measurement1);
}
Works well if you are showing a calculated value derived from a real world input.
Give it a try:
function format_my_number() {
$result = number_format(14301,2,',','.');
return $result;
}