How to remove the first zero in a decimal number without round off.
whenever a function detect the first zero in decimal stop it and remove the zero and excess decimals.
I tried this:
$number = 1.063;
echo floor_dec($number,$deg);
function floor_dec($number, $deg = null)
{
if ($deg == null)
return $number * 1000 / 1000;
else
return $number * pow(10, $deg) / pow(10, $deg);
}
Desired output:
1.063 -> output 1
1.30720-> output 1.3
1.3072-> output 1.3
1.823070 -> output 1.823
Tricky one using strpos()
function removeFirstZeroToEnd($number)
{
$str = explode('.',$number);
if(isset($str[1])){
// find first zero after decimal
$num = substr($str[1],0, strpos($str[1], "0"));
// adding zero will convert it to number
$number = ($str[0].'.'.$num) + 0;
}
return $number;
}
Seems like this would be a lot easier by just treating it as a string and then just get the desired substring and then convert back to float:
floatval(rtrim(substr($number, 0, strpos($number, 0)), "."));
Obligatory regex solution:
$numbers = [
123,
1.063,
1.30720,
1.3072,
1.823070
];
foreach ($numbers as &$n) {
$n = preg_replace ('~^([0-9]+(\.[1-9]+)?).*~','$1',$n);
}
print_r($numbers);
Output:
Array
(
[0] => 123
[1] => 1
[2] => 1.3
[3] => 1.3
[4] => 1.823
)
Related
I have numbers that are given to me in the following format:
12.2K
I would instead like to convert this number to display:
12200
The examples ive seen convert to K format, but I would like to convert from K format.
Is there an easy way to do this?
Thanks!
You mean, something like this? This will be able to convert thousands and millions, etc.
<?php
$s = "12.2K";
if (strpos(strtoupper($s), "K") != false) {
$s = rtrim($s, "kK");
echo floatval($s) * 1000;
} else if (strpos(strtoupper($s), "M") != false) {
$s = rtrim($s, "mM");
echo floatval($s) * 1000000;
} else {
echo floatval($s);
}
?>
<?php
$number = '12.2K';
if (strpos($number, 'K') !== false)
{
$number = rtrim($number, 'K') * 1000;
}
echo $number
?>
Basically, you just want to check if the string contains a certain character, and if it does, respond to it by taking it out and multiplying it by 1000.
An alternative method is to have the abbreviations in an array and use power of to calculate the number to multiply with.
This gives a shorter code if you have lots of abbreviations.
I use strtoupper to make sure it matches both k and K.
$arr = ["K" => 1 ,"M" => 2, "T" => 3]; // and so on for how ever long you need
$input = "12.2K";
if(isset($arr[strtoupper(substr($input, -1))])){ //does the last character exist in array as an key
echo substr($input,0,-1) * pow(1000, $arr[strtoupper(substr($input, -1))]); //multiply with the power of the value in array
// 12.2 * 1000^1
}else{
echo $input; // less than 1k, just output
}
https://3v4l.org/LXVXN
$result = str_ireplace(['.', 'K'], ['', '00'], '12.2K');
You can also expand this by other letters etc.
For example a number to 3 significant figures would be as follows
12345 => 12300
0.12345 => 0.123
0.012345 => 0.0123
There's nothing built in to round to a given number of significant figures (as opposed to a given number of digits.) Math to the rescue!
function toPrecision($number, $precision) {
if ($number == 0) return 0;
$exponent = floor(log10(abs($number)) + 1);
$significand =
round(
($number / pow(10, $exponent))
* pow(10, $precision)
)
/ pow(10, $precision);
return $significand * pow(10, $exponent);
}
$numbers = [
12345,
.12345,
.012345,
];
foreach($numbers as $number) {
echo toPrecision($number, 3), "\n";
}
Output:
12300
0.123
0.0123
In php, you could use round() function. It accepts two parameters, the number and precision, such as
echo round(12345, -2); # will result in 12300
echo round(0.12345, 3); # will result in 0.123
See the php manual on round() for more information.
There are several functions you can use for math operations. Here are a few examples
// 0.12345 => 0.123 - round half down
$result = round(0.12345, 3, PHP_ROUND_HALF_DOWN)
// 0.12345 => 0.124 - natural rounding
$result = round(0.12345. 3);
// 12345 => 12300
$result = round(12345, -2, PHP_ROUND_HALF_DOWN);
The round() function rounds integers by the given precision. Please respect the natural sorting. Higher than 5 means rounding up as far as you don 't mention the PHP_ROUND_HALF_DOWN constant.
You can use number_format() to achieve what you need.
$value = 0.12345;
$output = number_format($value, 3);
echo $output;
This will return: 0.123
Or you could wrap this withing a foreach loop if you need to go through an array, or alternatively create your own function to accept an integer and return the formatted value.
function formatNumber($int){
$number = number_format($int, 3);
return $number;
}
Or alternatively look at the link below to see if there is any other way you want to do this.
PHP.NET PAGE
What does the "B" do in this pack statement from Perl code?
$hce_hash=pack('B*', $hce_hash);
Is there an equivalent function in PHP?
PHP’s pack doesn’t support a format of B*, but it does support H*. In Perl, you could emulate it with
sub pack_Bstar {
my($bits) = #_;
my $Hstar;
my $nybble = 0;
for (my $i = 0; $i < length $bits; ++$i) {
$nybble *= 2;
$nybble += int substr($bits, $i, 1);
if ($i % 4 == 3) {
$Hstar .= sprintf "%x", $nybble;
$nybble = 0;
}
}
my $pad = 4 - length($bits) % 4;
if ($pad != 4) {
$nybble = ($nybble << $pad);
$Hstar .= sprintf "%x", $nybble;
}
pack "H*", $Hstar;
}
The code above is not idiomatic Perl, but translation to PHP should be straightforward.
The H* format wants a hex string with high nybble (4 bits) first. The code above chews off four bits at a time to compute each nybble value. For example, for a bit string of 1011, tracing the algorithm gives
nybble = 0
nybble = 2 * 0 + 1 = 1
nybble = 2 * 1 + 0 = 2
nybble = 2 * 2 + 1 = 5
nybble = 2 * 5 + 1 = 11
10112 is indeed 1110, which is b16. If the last nybble is incomplete (between one and three bits), we left-shift the bit the appropriate number of places. This has the effect of zero-padding on the right.
Tests:
my #tests = (
["01001010011101010111001101110100" => "Just"],
["0110000101101110011011110111010001101000011001010111001" => "another"],
["01010000010010000101000000101111010100000110010101110010011011" => "PHP/Perl"],
["01101000011000010110001101101011011001010111001000101100" => "hacker,"],
);
for (#tests) {
my($input,$expect) = #$_;
my $got = pack_Bstar $input;
print "$input: ", ($got eq $expect ? "PASS" : "FAIL"), " ($got)\n";
}
Output:
01001010011101010111001101110100: PASS (Just)
0110000101101110011011110111010001101000011001010111001: PASS (another)
01010000010010000101000000101111010100000110010101110010011011: PASS (PHP/Perl)
01101000011000010110001101101011011001010111001000101100: PASS (hacker,)
pack 'B*', $s returns the bytes represented by the string of 0 and 1 characters that form up the string in $s. The value of $s is right-padded with zeros to a length divisible by 8 if necessary.
For example,
pack 'B*', '0100101000110101'
results in
chr(0b01001010) . chr(0b00110101);
As others have noted, PHP's pack() does not support the B template, which in Perl's pack() turns a bitstring, represented as a literal string of 0 and 1 characters, into a packed byte string with 8 bits per byte.
However, since PHP's pack() does support the H template, which does the same except for hexadecimal digits instead of bits, we can emulate Perl's B template in PHP by first using base_convert() to turn the bits into hex digits and then packing those:
function pack_B( $bits, $len = false ) {
// truncate input to desired length, if given:
if ( $len === false ) $len = strlen( $bits );
else $bits = substr( $bits, 0, $len );
// pad input with zeros to next multiple of 4 above $len:
$hexlen = (int)( ($len + 3) / 4 );
$bits = str_pad( $bits, 4*$hexlen, "0" );
// split input into chunks of 4 bits, convert each to hex and pack them:
$nibbles = str_split( $bits, 4 );
foreach ( $nibbles as $i => $nibble ) {
$nibbles[$i] = base_convert( $nibble, 2, 16 );
}
return pack( "H*", implode( "", $nibbles ) );
}
(The reason we can't just feed the whole input string to base_convert() is that it stores its intermediate result as a PHP float, and thus doesn't produce correct results for numbers too large to be accurately represented by a float. Doing it one hex digit at a time works fine, however.)
I have a price "0,10" or "00000,10"
Now when i try
number_format($price, 2, ',', '')
I get 0,00.
How can i fix this? I want 0,10 $.
I don't want rounding.
Or when i have 5,678, i get 5,68. But i want 5,67.
Several people have mentioned rounding it to 3 and then dropping the last character. This actually does not work. Say you have 2.9999 and round it to 3 it's 3.000.
This is still not accurate, the best solution is this:
$price = '5.678';
$dec = 2;
$price = number_format(floor($price*pow(10,$dec))/pow(10,$dec),$dec);
What this does is takes the price and multiplies it by 100 (10^decimal) which gives 567.8, then we use floor to get it to 567, and then we divide it back by 100 to get 5.67
You can increase the size of the number before rounding down with floor:
$price = floor($price * 100) / 100;
$formatted = number_format($price, 2, ',', '');
Another solution, which may give better precision since it avoids floating-point arithmetic, is to format it with three decimals and throw away the last digit after formatting:
$formatted = substr(number_format($price, 3, ',', ''), 0, -1);
you should convert comma-filled number back to normal decimal before with str_replace.
$number = str_replace(",", ".", $number);
and then you can use number_format
"00000,10" is a string. You should a decimal point. To get the desired behaviour, you could use:
echo substr(number_format(str_replace(',', '.', $price), 3, ',', ''), 0, -1);
Use this (needs activated intl PHP extension)
$numberFmtCurrency = new NumberFormatter('de_AT', NumberFormatter::CURRENCY);
$numberFmtCurrency->setAttribute(NumberFormatter::ROUNDING_INCREMENT, 0);
$numberFmtCurrency->formatCurrency(328.13, 'EUR'); // prints € 328.13 (and not 328.15)
If you are literally just wanting to clear leading zeroes and just limit the length, rather than round to a certain amount of decimal places, a more generalised solution could be this function:
function cutafter($string,$cutpoint,$length)
{
$temp = explode($cutpoint,$string);
$int = $temp[0];
$sub = $temp[1];
return number_format($int,0).','.substr($sub,0,$length);
}
Example:
$number = "005,678";
$answer = cutafter($number,",",2);
$answer now equals "5,67"
Just before number_format is executed the string "0,10" is converted by php to an number. because php always uses the engish notation the it won't look after the comma.
echo "4 apples" + 2;
output: 6
The " apples" part is ignored just as your ",10" is ignored.
Converting the "," to a "." allows php to see the other digits.
$price = str_replace(',', '.', '0,10');
number_format($price, 2, ',', '');
My problem was that html validator error messege thar number_format() argument is not double.
I solved this error message by placing floatval for that argument like number_format(floatval($var),2,'.',' ') and that is working good.
function format_numeric($value) {
if (is_numeric($value)) { // is number
if (strstr($value, ".")) { // is decimal
$tmp = explode(".", $value);
$int = empty($tmp[0]) ? '0' : $tmp[0];
$dec = $tmp[1];
$value = number_format($int, 0) . "." . $dec;
return $value;
}
$value = number_format($value);
return $value;
}
return $value; // is string
}
Unit Testing:
Passed / 1100000 => 1,100,000
Passed / ".9987" => .9987
Passed / 1100.22 => 1,100.22
Passed / 0.9987 => 0.9987
Passed / .9987 => 0.9987
Passed / 11 => 11
Passed / 11.1 => 11.1
Passed / 11.1111 => 11.1111
Passed / "abc" => "abc"
See this answer for more details.
function numberFormat($number, $decimals = 0, $decPoint = '.' , $thousandsSep = ',')
{
$negation = ($number < 0) ? (-1) : 1;
$coefficient = pow(10, $decimals);
$number = $negation * floor((string)(abs($number) * $coefficient)) / $coefficient;
return number_format($number, $decimals, $decPoint, $thousandsSep);
}
I have some double fields in my database and when echoing the fields out in my php I get .00 at the end of the values.
How do I get the .00 not to display, but display if there is a value?
You can use str_replace to remove the ".00" from the values.
$value = 10.00;
echo str_replace('.00', '', $value); // 10
$value = 10.52;
echo str_replace('.00', '', $value); // 10.52
echo (int)$double;
will simply strip off the decimal places. if you merely want to hide 'zero' decimals (10.00 -> 10), but leave non-zero decimals (10.1 -> 10.1), then you'd need to do some processing:
echo preg_replace('/\.0+$/', '', $double);
which would handle any number of zeroes after the decimal place, but leave non-zeroes in place.
if (fmod($number, 1) == 0)
{
$number = intval($number);
}
else
{
$number = round($number, 2);
}
Or just use round() [# ideone.com]:
var_dump(round($number = 5.00, 2)); // 5
var_dump(round($number = 5.01, 2)); // 5.01
For an arbitrary number of 0s at the end of the number:
$number = rtrim($number,".0");
Examples:
Input : 1.00
Result: 1
Input : 1.25
Result: 1.25
Input : 1.40
Result: 1.4
Input : 1.234910120000
Result: 1.23491012
select number,if(number % 1 = 0,cast(number as unsigned),number)
from table