I got a string value in number, like 2345.567, I want to keep only one character after the decimal. I dont want to use any Number function, I just want to remove any number of character after the period (dot)?
If you are worried about the input being not a number, you should validate it first:
function round_number($number, $precision = 1) {
if(!is_numeric($number)) {
throw new InvalidArgumentException("round_number() expects a numeric type, instead received '".gettype($number)."'");
}
return round($number, $precision);
}
Reference:
round($number, $precision)
is_numeric($var)
$number = 2345.567;
$new_numb = number_format($number,1);
$new_numb will be treated as string
<?php
$str = "2345.567";
$ip = explode('.',$str);
echo $ip[0].".".substr($ip[1],0,1)
?>
after edit:
<?php
// case: if there is no decimal place
echo $ip[0]."".($ip[1]?".".substr($ip[1],0,1):'');
?>
Formatted string output can be done with number_format or with the printf family of functions.
print number_format((float)$string, 1);
printf("%.1f", $string);
Assuming the input is guaranteed to be well-formed...
substr($numberString, 0, strpos(".", $numberString) + 2);
You can do it as follows
$string = "234567.2345";
if(!is_numeric($string)) {
$output = $string;
}
else{
$output = round($string,1);
}
output will be
234567.2
if string is given as 234
output will be 234.o
if string is given other than number "asdf"
output will be asdf
Related
I've tried casting to float and number_format but float will always round at two and number_format is fixed on the amount of decimals you specify.
So how can I do this like the following conversion
11.2200 -> 11.22
11.2000 -> 11.20
11.2340 -> 11.234
$money1 = 68.75;
$money2 = 54.35;
$money = $money1 + $money2;
// echo $money will output "123.1";
$formatted = sprintf("%01.2f", $money);
// echo $formatted will output "123.10"
This might help, You can use sprintf given by PHP.
You can use float casting
echo (float) 11.2200;
echo "<br/>";
echo (float) 11.2000;
echo "<br/>";
echo (float) 11.2340;
and you have to check number of digits after decimal point and than get value like below :
$val=(float) 11.2000;
if(strlen(substr(strrchr($val, "."), 1))<2){
echo number_format($val,2);
}
You may use the round() function for this.
i-e round(number,precision,mode);
Example:
echo(round(11.2200,2));
Output
11.22
Thanks
Not sure if you need a fix for this anymore, but I just ran into the same problem and here's my solution:
$array = array(11.2200, 11.2000, 11.2340);
foreach($array as $x)
{
// CAST THE PRICE TO A FLOAT TO GET RID OF THE TRAILING ZEROS
$x = (float)$x
// EXPLODE THE PRICE ON THE DECIMAL (IF IT EXISTS)
$pieces = explode('.',$x);
// IF A SECOND PIECE EXISTS, THAT MEANS THE FLOAT HAS AT LEAST ONE DECIMAL PLACE
if(isset($pieces[1]))
{
// IF THE SECOND PIECE ONLY HAS ONE DIGIT, ADD A TRAILING ZERO TO FORMAT THE CURRENCY
if(strlen($pieces[1]) == 1)
{
$x .= '0';
}
}
// IF NO SECOND PIECE EXISTS, ADD A .00 TO IT TO FORMAT THE CURRENCY VALUE
else
{
$x .= '.00';
}
}
I'm trying to replace some characters from a string using str_pad and I can't get it to work at all and I have no idea why it doesn't work.
Code:
<?php
$t = "abcdefghij";
$t = str_pad($t, 4, "0");
echo $t;
?>
Expected:
abcd000000
Result:
abcdefghij
I also tried:
$t = sprintf("%04x", $t);
Which results in:
0000
If you have a variable length string, you can use the below
$str = "abcdefghijzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz";
$head = substr($str, 0, 4); // construct the first part of your string
$tail = substr($str, 4); // get the second part of the string
print $head . str_repeat('0',strlen($tail));
// or all in one go
$number = 4;
print substr($str, 0, $number) . str_repeat('0',strlen(substr($str, $number)));
//will output
//abcd0000000000000000000000000000000000000
To replace everything except the first x number of characters in your string.
Because your string is longer than four characters so str_pad() will not append anything to it.
If the value of pad_length is negative, less than, or equal to the length of the input string, no padding takes place, and input will be returned.
If you want to always append four zeros just concatenate them onto your string:
<?php
$t = "abcdefghij";
$t = '0000' . $t;
echo $t;
?>
What you are looking for is a mixture of str_pad and substr, using the two like this:
echo str_pad(substr($str, 0, 4), strlen($str), '0', STR_PAD_RIGHT);
Will give you output like this:
abcd000000
You may however, need to tweak the numbers to get your desired results.
Here is a function you can use:
function pad($str, $length, $value= '0', $side = STR_PAD_RIGHT){
return str_pad(substr($str, 0, $length), strlen($str), $value, $side);
}
echo pad('abcdefghij', 4);
You need a different functions. str_pad() adds to the string and you are wanting to replace:
$t = substr_replace($t, str_repeat('0', strlen($t)-4), 4);
I have strings of numbers like this:
- 00986756849
- 007478599700
- 004583930237345
I need to convert these strings of numbers into new numbers with the last two decimal values in PHP, ie:
- 009867568.49
- 0074785997.00
- 0045839302373.45
How to?
Get the string value . use substr_replace to replace a sub string or insert a substring to a specific position in the string :)
$str = "00986756849";
substr_replace($str,".",strlen($str)-2,0);
$intNumber = (int) $stringNumber;
$decimalNumber = sprintf('%02d', $intNumber);
You can try this
//$str = "10";
$str = "00986756849";
$str_length = strlen($str);
if($str_length>2)
{
$output = substr_replace($str,".",$str_length-2,0);
}
else
{
$output = substr_replace($str,".00",$str_length,0);
}
echo $output;
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);
I need help converting a string that contains a number in scientific notation to a double.
Example strings:
"1.8281e-009"
"2.3562e-007"
"0.911348"
I was thinking about just breaking the number into the number on the left and the exponent and than just do the math to generate the number; but is there a better/standard way to do this?
PHP is typeless dynamically typed, meaning it has to parse values to determine their types (recent versions of PHP have type declarations).
In your case, you may simply perform a numerical operation to force PHP to consider the values as numbers (and it understands the scientific notation x.yE-z).
Try for instance
foreach (array("1.8281e-009","2.3562e-007","0.911348") as $a)
{
echo "String $a: Number: " . ($a + 1) . "\n";
}
just adding 1 (you could also subtract zero) will make the strings become numbers, with the right amount of decimals.
Result:
String 1.8281e-009: Number: 1.0000000018281
String 2.3562e-007: Number: 1.00000023562
String 0.911348: Number: 1.911348
You might also cast the result using (float)
$real = (float) "3.141592e-007";
$f = (float) "1.8281e-009";
var_dump($f); // float(1.8281E-9)
Following line of code can help you to display bigint value,
$token= sprintf("%.0f",$scienticNotationNum );
refer with this link.
$float = sprintf('%f', $scientific_notation);
$integer = sprintf('%d', $scientific_notation);
if ($float == $integer)
{
// this is a whole number, so remove all decimals
$output = $integer;
}
else
{
// remove trailing zeroes from the decimal portion
$output = rtrim($float,'0');
$output = rtrim($output,'.');
}
I found a post that used number_format to convert the value from a float scientific notation number to a non-scientific notation number:
Example from the post:
$big_integer = 1202400000;
$formatted_int = number_format($big_integer, 0, '.', '');
echo $formatted_int; //outputs 1202400000 as expected
Use number_format() and rtrim() functions together. Eg
//eg $sciNotation = 2.3649E-8
$number = number_format($sciNotation, 10); //Use $dec_point large enough
echo rtrim($number, '0'); //Remove trailing zeros
I created a function, with more functions (pun not intended)
function decimalNotation($num){
$parts = explode('E', $num);
if(count($parts) != 2){
return $num;
}
$exp = abs(end($parts)) + 3;
$decimal = number_format($num, $exp);
$decimal = rtrim($decimal, '0');
return rtrim($decimal, '.');
}
function decimal_notation($float) {
$parts = explode('E', $float);
if(count($parts) === 2){
$exp = abs(end($parts)) + strlen($parts[0]);
$decimal = number_format($float, $exp);
return rtrim($decimal, '.0');
}
else{
return $float;
}
}
work with 0.000077240388
I tried the +1,-1,/1 solution but that was not sufficient without rounding the number afterwards using round($a,4) or similar