split a number into whole number , decimal points and trailing digits - php

I have variables of bitcoin values all rounded to 8 decimal places. eg
1.00645600
I need a way in jQuery or php to get the whole number [1], The decimal values [006456], and trailing zeros [00]. I have already tried php substr but it messed up with the results since im dealing with variables.

Simple and general solution in PHP without involving regular expressions (that is an option also):
$number = '1.00645600';
$flooredNumber = floor($number); // 1
$decimalPart = (string) (floatval($number) - $flooredNumber); // 0.006456
$decimals = str_replace('0.', '', $decimalPart); // 006456
$trailingZeros = str_replace(rtrim($number, '0'), '', $number); // 00

substr
Returns the portion of string specified by the start and length parameters.
http://php.net/manual/en/function.substr.php
If the numbers in your string are always in the same position you can use substr() to get the desired values:
$str = '1.00645600';
echo substr($str, 0, 1)."\r\n";
echo substr($str, 2, 2)."\r\n";
echo substr($str, 2, 6)."\r\n";
Output:
1
00
006456

Perhaps, this way?
<?php
$i = '1.00645600';
echo rtrim(rtrim($i, '0'), '.');
?>

Related

Splitting strings through php to query mysql

I need to split a string in two so I can do a SELECT query in my DB. For example, I have the number '0801'. I need to split that number into '08' and '01'. How do I manage to do that?
This is easy to do using the substr() function, which lets you pull out parts of a string. Given your comment that you always have a four-digit number and want it split into two two-digit numbers, you want this:
$input = "0801";
$left = substr($input, 0, 2);
$right = substr($input, 2);
echo "Left is $left and right is $right\n";
According to your comment
The first 2 numbers. It's allways a 4 digit number and I allways need
to split it in 2 two digit numbers
You can simply use
$value = '0801';
$split = str_split($value, 2);
var_dump($split[0]);
var_dump($split[1]);
Just keep in mind $value variable should always be of a string type, not int.
you can use str_split and list
$str = '0801';
list($first,$second) = str_split($str,2);
echo $first;
// 08
echo $second;
// 01
No one gave a MySQL answer yet...
If you're selecting that number..
SELECT
SUBSTR(colname, 0, 2) as firstpart,
SUBSTR(colname, 2, 2) as secondpart
FROM table

PHP add thousand separators to number and keep leading zeros

I'm trying to add thousand separators to a number using PHP and at the same time keep the leading zeros (It's part of the design of an app that the leading 0s stay so that people can see the number grow towards the set target - a 6 figure number).
My initial attempt was to use str_pad to add the leading zeros if the current number calculated was less than 6 figures long. Then to add the commas I used number_format. The obvious issue is that number_format removes the leading 0s.
$num = 550;
$num_padded = str_pad($num, 6, '0', STR_PAD_LEFT);
echo number_format($num_padded);
So that returns 550 instead of 000,550
Does anyone know of a reliable way to achieve the format I'm looking for?
Thanks!
I have in mind this simple trick:
function padAndFormat($number, $length)
{
if(strlen($number)>=$length)
{
return number_format($number);
}
$number = number_format('1'.str_pad($number, $length-1, '0', STR_PAD_LEFT));
$number[0] = '0';
return $number;
}
//var_dump(padAndFormat('517', 6)); //string(7) "000,517"
another way to do this is to use sprintf
// length can be changed, here is 6
implode(',',str_split(sprintf('%06d', $this->iterator),3));
the result will be :
input
result
4
000,004
400
000,400
23560
023,560
1234567
1,234,567
it can be improved by reading the length, and computing automatically the final length, multiple of 3
I don't need number format but I need that comma! :)
<?php
$zeroes=0;
$num = 550;
$num_padded = str_pad($zeroes, 3, '0', STR_PAD_LEFT);
$num_padded = str_pad($num_padded,strlen($num_padded)+strlen($zeroes), ',', STR_PAD_RIGHT);
$num_padded = str_pad($num_padded,strlen($num_padded)+strlen($num), $num, STR_PAD_RIGHT);
echo $num_padded;
OUTPUT :
000,550
One Liner with PHP string manipulation. Works for any number of digits:
function pad($number, $min_digits){
return strrev(implode(",",str_split(str_pad(strrev($number), $min_digits, "0", STR_PAD_RIGHT),3)));
}
/* Output for 9 digits
0,000,001
0,000,012
0,000,123
0,001,234
0,012,345
0,123,456
1,234,567
12,345,678
123,456,789
/**/

function to return the numeric value

What would be an elegant way of doing this?
I have this -> "MC0001" This is the input. It always begins with "MC"
The output I'd be aiming with this input is "MC0002".
So I've created a function that's supposed to return "1" after removing "MC000". I'm going to convert this into an integer later on so I could generate "MC0002" which could go up to "MC9999". To do that, I figured I'd need to loop through the string and count the zeros and so on but I think I'd be making a mess that way.
Anybody has a better idea?
This should do the trick:
<?php
$string = 'MC0001';
// extract the part succeeding 'MC':
$number_part = substr($string, 2);
// count the digits for later:
$number_digits = strlen($number_part);
// turn it into a number:
$number = (int) $number_part;
// make the next sequence:
$next = 'MC' . str_pad($number + 1, $number_digits, '0', STR_PAD_LEFT);
using filter_var might be the best solution.
echo filter_var("MC0001", FILTER_SANITIZE_NUMBER_INT)."\n";
echo filter_var("MC9999", FILTER_SANITIZE_NUMBER_INT);
will give you
0001
9999
These can be cast to int or just used as they are, as PHP will auto-convert anyway if you use them as numbers.
just use ltrim to remove any leading chars: http://php.net/manual/en/function.trim.php
$str = ltrim($str, 'MC0');
$num = intval($str);
<php
// original number to integer
sscanf( $your_string, 'MC%d', $your_number );
// pad increment to string later on
sprintf( 'MC%04u', $your_number + 1 );
Not sure if there is a better way of parsing a string as an integer when there are leading zero's.
I'd suggest doing the following:
1. Loop through the string ( beginning at location 2 since you don't need the MC part )
2. If you find a number thats bigger than 0, stop, get the substring using your current location and the length of the string minus your current location. Cast to integer, return value.
You can remove the "MC" par by doing a substring operating on the string.
$a = "MC0001";
$a = substr($a, 2); //Lengths of "MC"
$number = intval($a); //1
return intval(str_replace($input, 'MC', ''), 10);

Advanced Php Number Formatting

I want to have a PHP number formatted with a minimum of 2 decimal places and a maximum of 8 decimal places. How can you do that properly.
Update: I'm sorry, my question is say I have number "4". I wish for it to display as "4.00" and if I have "2.000000001" then it displays as "2.00" or if I have "3.2102" it will display as such. There is a NSNumber formatter on iPhone, what is the equivalent in PHP.
This formats the $n number for 8 decimals, then removes the trailing zero, max 6 times.
$s = number_format($n, 8);
for($i=0; $i<8-2; $i++) {
if (substr($s, -1) == '0')
$s = substr($s, 0, -1);
}
print "Number = $s";
Use sprintf() to format a number to a certain number of decimal places:
$decimal_places = 4;
$format = "%.${decimal_places}f";
$formatted = sprintf($format,$number);
I don't understand why you would want to display numbers to an inconsistent degree of accuracy. I don't understand what pattern you're trying to describe in your comment, either.
But let us suppose that you want the following behaviour: you want to express the number to 8 decimal places, and if there are more than 2 trailing zeroes in the result, you want to remove the excess zeroes. This is not much more difficult to code than it is to express in English. In pseudocode:
$mystring = string representation of number rounded to 8 decimal places;
while (last character of $mystring is a 0) {
chop off last character of $mystring;
}
Check the number format function:
<?php
$num = 43.43343;
$formatted = number_format(round((float) $num, 2), 2);
?>
http://php.net/manual/en/function.number-format.php
Using preg_match just get the zero ending with and then rtim it
<?php
$nn = number_format(10.10100011411100000,13);
preg_match('/[0]+$/',$nn,$number);
if(count($number)>0){
echo rtrim($nn,$number[0]);
}
Hope it will help you.

Add a period to the middle string PHP

It will actually be a decimal but that is not the main point. I will have a set of numbers like:
8976
8765
3454
3453
10198
What I am wanting to do is add a decimal 2 places from the right. So the first would be 89.76 and so forth.
Can't you just multiply each by 0.01?
$formatted = number_format($unformatted_number / 100, 2, '.', '');
2 - decimal places
'.' - decimal separator
'' - thousands separator
docs for the function are here.
try this
$number = 8976;
$number = (float)$number/100;
results:
89.76
You may have to do some checking to see how many digits the number is, i.e 89768 would be devided by 1000 and so on.
Comments are available,
//the string you need to split
$string = "123456";
// read from right 2 character
$rightNums = substr($string, -2, 2);
// maximum 100 character to the left defined now
$otherNums = substr($string, -4, 100);
// pront them just with . between
echo $otherNums.".".$rightNums; ?>
hope it help much.
Try with this
$tmpString = substr("8976", 0, -2);
$finalString = str_replace($tmpString, "." . $tmpString, "8976");
echo $finalString;

Categories