Remove useless zero digits from decimals - php

I need to delete useless zero but i have problem with (float) and number_format()
I have number like 0.00000010 and i need 0.0000001 but i have 0.0000 without number_format its good
My code
$number = (float)$number;
$number_array = explode('.', $number);
$left = $number_array[0];
$right = $number_array[1];
$number = number_format($number, strlen($right));
http://codepad.org/ondL9bg1

This should do it:
$number = rtrim($number, '0');
rtrim takes the character(s) to trim as a second (optional) argument.
If you want it to work also for integers (eg. 1000), try this:
if (false !== strpos($number, '.'))
$number = rtrim($number, '0');
Even better, to remove trailing dot in numbers like 0.00000:
if (false !== strpos($number, '.'))
$number = rtrim(rtrim($number, '0'), '.');

Related

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

Adding a string and an integer in php

I'm trying to add a 1 in front of my binary code and this is how I'm going about it:
if I have 0101, for example, then I'd add a number with 4 zeroes, like 10000 so it would become 10101. Here's my code:
$fill = strlen($string);
$number = '1';
$add = str_pad($number, $fill, '0', STR_PAD_RIGHT);
$m1 = $string + $add;
The problem is the output for that is something like 1.random number e+Random number
assuming $string is your "0101" string, you could just do $m1 = '1'.$string;
My previous answer was wrong because the length of the string is potentially variable and str_pad requires you to know the length. This will work, but it doesn't look so elegant:
if (strpos($string, '0') === 0) {
$string = '1' . $string;
}

align decimals in array of currency values

I've tried to write a function that will take an array of different amounts and align the decimal places, by adding the appropriate amount of to each number with a lesser length than the number with longest length.
It seems pretty long though, and I wonder if anyone has some insight on how I could make is shorter and more efficient.
$arr = array(12, 34.233, .23, 44, 24334, 234);
function align_decimal ($arr) {
$long = 0;
$len = 0;
foreach ( $arr as &$i ){
//change array elements to string
(string)$i;
//if there is no decimal, add '.00'
//if there is a decimal, add '00'
//ensures that there are always at least two zeros after the decimal
if ( strrpos( $i, "." ) === false ) {
$i .= ".00";
} else {
$i .= "00";
}
//find the decimal
$dec = strrpos( $i, "." );
//ensure there are only two decimals
//$dec+3 is the decimal plus two characters
$i = substr_replace($i, "", $dec+3);
//if $i is longer than $long, set $long to $i
if ( strlen($i) >= strlen($long) ) {
$long = $i;
}
}
//locate the decimal in the longest string
$long_dec = strrpos( $long, "." );
foreach ( $arr as &$i ) {
//difference between $i and $long position of the decimal
$z = ( $long_dec - strrpos( $i, "." ) );
$c = 0;
while ( $c <= $z ) {
//add a for each number of characters
//between the two decimal locations
$i = " " . $i;
$c++;
}
}
return $arr;
}
it works okkaaay... just seems really verbose. I'm sure there are a million ways to make it much shorter and more professional. Thanks for any ideas!
Code:
$array = array(12, 34.233, .23, 44, 24334, 234);;
foreach($array as $value) $formatted[] = number_format($value, 2, '.', '');
$length = max(array_map('strlen', $formatted));
foreach($formatted as $value)
{
echo str_repeat(" ",$length-strlen($value)).$value."<br>";
}
Output:
12.00<br>
34.23<br>
0.23<br>
44.00<br>
24334.00<br>
234.00<br>
Rendered by browser:
12.00
34.23
0.23
44.00
24334.00
234.00
Is using a space a requirement for the display? If you don't mind having "30" coming out as "30.000" you could use the number_format to do most of the work for you, after you figured out the max number of decimal places to use.
$item = "40";
$len = 10;
$temp = number_format($item,$len);
echo $temp;
Another would be to use sprintf to format:
$item = "40";
$len = 10;
$temp = sprintf("%-{$len}s", $item);
$temp = str_replace(' ', ' ',$temp);
echo $temp;
Have you considered using HTML elements alongside CSS alignment to do this for you?
For instance:
<div style="display:inline-block; text-align:right;">$10.00<br />$1234.56<div>
This would ease the issue of using spaces to manually adjust the alignment. Since you're aligning to the right and there are two decimal places, the decimals will line up as you wish. You could also do this using a <table> and in both scenarios, you're able to simply retrieve the full value through JS if need be.
Lastly, using spaces assumes you're using a fixed-width font which may not necessarily be the case. CSS alignment allows you to handle this much more eloquently.

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;
}

Split a number by decimal point in php

How do I split a number by the decimal point in php?
I've got $num = 15/4; which turns $num into 3.75. I would like to split out the 3 and the 75 parts, so $int = 3 and $dec = 75. My non-working code is:
$num = 15/4; // or $num = 3.75;
list($int, $dec) = split('.', $num);
but that results in empty $int and $dec.
Thanks in advance.
If you explode the decimal representation of the number, you lose precision. If you don't mind, so be it (that's ok for textual representation). Take the locale into account! We Belgians use a comma (at least the non-programming ones :).
If you do mind (for computations e.g.), you can use the floor function:
$num = 15/4
$intpart = floor( $num ) // results in 3
$fraction = $num - $intpart // results in 0.75
Note: this is for positive numbers. For negative numbers you can invert the sign, use the positive approach, and reinvert the sign of the int part.
$num = 15/4; // or $num = 3.75;
list($int, $dec) = explode('.', $num);
Try explode
list($int,$dec)=explode('.', $num);
as you don't really need to use a regex based split. Split wasn't working for you as a '.' character would need escaping to provide a literal match.
$int = $num > 0 ? floor($num) : ceil($num);
$dec = $num - $int;
If you want $dec to be positive when $num is negative (like the other answers) you could do:
$dec = abs($num - $int);
$num = 3.75;
$fraction = $num - (int) $num;
In case when you don't want to lose precision, you can use these:
$number = 10.10;
$number = number_format($number, 2, ".", ",");
sscanf($number, '%d.%d', $whole, $fraction);
// you will get $whole = 10, $fraction = 10
This works for positive AND negative numbers:
$num = 5.7;
$whole = (int) $num; // 5
$frac = $num - (int) $num; // .7
$num = 15/4;
substr(strrchr($num, "."), 1)

Categories