PHP string to decimal with .00 - php

so I am trying to achieve this
I have decimal 1.00 Which when i convert to float becomes 1.0. So my question is how can i save the last zero and at the same time to be float not a string if i use number_format(1.0,2) it becomes "1.00" Which is string but i need to be decimal with the last zero. This is what i tried so far
<?php
$decimal = "1.0";
$decimalToFloat = floatval($decimal) // It becomes 1.0
$decimalToFloat = number_format($decimal,2) // It becomes "1.00" !!! String not a float !!!
// The result which i want is 1.00 not "1.00"

Let me start by saying that this is an XY problem, as you don't need to convert from a string to an integer in PHP, as PHP will coerce the type for you automatically.
In addition to this, there is no need to specify the number of places on a decimal, as 1 is exactly equal to 1.0, and 1.0 is exactly equal to 1.00. In fact, forcibly casting the string showcases that PHP will automatically trim the decimal places:
$decimal = "1.0";
echo number_format((float)$decimal, 2, '.', ''); // "1.00" (string)
echo (int)number_format((float)$decimal, 2, '.', ''); // 1 (int)
echo (float)number_format((float)$decimal, 2, '.', ''); // 1 (float)
It is impossible to showcase an int or float with decimal places comprised purely of zeros in PHP. Though you do not need to do this; you can simply use the whole numbers instead:
echo 1 + 1.01; // 2.01 (float)
Hope this helps! :)

Related

How to transform last two numbers to decimal (int to float) in php?

I need transform 100 to 1.00, 345 to 3.45 or any number with 3 digits or more to record in db like a decimal.
Don't need add .00, just transform last two numbers in decimal.
I try number_format($num, 2) but is wrong.
It seems, that you want to divide your numbers to 100, so using number_format() with the appropriate $decimal_separator and $thousands_separator is an option:
<?php
echo number_format($num / 100, 2, '.', '');
?>
Since you are converting from an integer to a float, you can achieve this simply by dividing the number by 100.
$input = 100;
$value = floatval($input) / 100;
$value = number_format($value, 2);
echo $value;
You may then use number_format (as you were using before) to force two decimal places after any evenly divided float numbers (such as 100).
Demo: PHP Sandbox Example

How to remove 0(zero number) from php variable?

I try to remove zero number from php variable using php function, but not work.
I try to use round or floor or ceil but not work.
How can I do that?
2.00 ===> 2
2.05 ===> 2.05 (not remove zero)
2.50 ===> 2.5
2.55 ===> 2.55 (not remove zero)
You must be having string variable. Please convert it to float as (float)$var and you will lose these zeros if you print the result out.
Other option is to use rtrim on string to remove the 0 and . from the end. see examples here http://php.net/rtrim
Try this:
number_format((float)$your_number, 2, '.', '');
I had the same problem. Function number_format() returns number as string so it will not remove zeros at the end.
Try this :
$list = array("2.00", "2.05", "2.50", "2.55");
foreach($list as $val)
echo (double) $val . "</br>";
Output:
2
2.05
2.5
2.55
In PHP you can cast the value to a Float Type (double, float, real), which will drop all leading or trailing zeros (after the decimal).
2.5 === (double) "2.50"
Be aware, however, that this does not format your number other than removing the 0's (this does not ensure a money format). For formatting, see number_format().
2.5 === (double) number_format('2.501', 2, '.', '');
Example:
(float) 2.00 === 2
(float) 2.05 === 2.05 // (not remove zero)
(float) 2.50 === 2.5
(float) 2.55 === 2.55 // (not remove zero)
And a proof: http://ideone.com/wimBHm
An interesting thing to note is that the test (float) 2.00 === 2 actually does not pass, this is because 2 is actually of type (int), and therefore fails the === test, however, as you can see, the output is exactly what you are looking for.
$price = '2.00';
$price2 = '2.50';
$price3 = '2.05';
function formatPrice($price)
{
/* Format number with 2 decimal places, then remove .00, then right trim any 0 */
return rtrim(str_replace('.00', '', number_format($price, 2)), '0');
}
echo formatPrice($price); //2
echo formatPrice($price2); //2.5
echo formatPrice($price3); //2.05

PHP float with 2 decimal places: .00

When I do this typecasting:
(float) '0.00';
I get 0. How do I get 0.00 and still have the data type as a float?
A float doesn't have 0 or 0.00 : those are different string representations of the internal (IEEE754) binary format but the float is the same.
If you want to express your float as "0.00", you need to format it in a string, using number_format :
$numberAsString = number_format($numberAsFloat, 2);
As far as i know there is no solution for PHP to fix this. All other (above and below) answers given in this thread are nonsense.
The number_format function returns a string as result as written in PHP.net's own specification.
Functions like floatval/doubleval do return integers if you give as value 3.00 .
If you do typejuggling then you will get an integer as result.
If you use round() then you will get an integer as result.
The only possible solution that i can think of is using your database for type conversion to float. MySQL for example:
SELECT CAST('3.00' AS DECIMAL) AS realFloatValue;
Execute this using an abstraction layer which returns floats instead of strings and there you go.
JSON output modification
If you are looking for a solution to fix your JSON output to hold 2 decimals then you can probably use post-formatting like in the code below:
// PHP AJAX Controller
// some code here
// transform to json and then convert string to float with 2 decimals
$output = array('x' => 'y', 'price' => '0.00');
$json = json_encode($output);
$json = str_replace('"price":"'.$output['price'].'"', '"price":'.$output['price'].'', $json);
// output to browser / client
print $json;
exit();
Returns to client/browser:
{"x":"y","price":0.00}
0.00 is actually 0. If you need to have the 0.00 when you echo, simply use number_format this way:
number_format($number, 2);
You can show float numbers
with a certain number of decimals
with a certain format (localised)
i.e.
$myNonFormatedFloat = 5678.9
$myGermanNumber = number_format($myNonFormatedFloat, 2, ',', '.'); // -> 5.678,90
$myAngloSaxonianNumber = number_format($myNonFormatedFloat, 2, '.', ','); // -> 5,678.90
Note that, the
1st argument is the float number you would like to format
2nd argument is the number of decimals
3rd argument is the character used to visually separate the decimals
4th argument is the character used to visually separate thousands
Use the number_format() function to change how a number is displayed. It will return a string, the type of the original variable is unaffected.
try this
$nom="5695.5";
number_format((float)($nom), 2, '.', ','); // -> 5,695.50
$nom="5695.5215";
number_format((float)($nom), 2, '.', ','); // -> 5,695.52
$nom="5695.12";
number_format((float)($nom), 0, '.', ','); // -> 5,695
//use round()
$nom="5695.12";
number_format((float)round($nom), 2, '.', ','); // -> 5,695.00
$nom="5695.52";
number_format((float)round($nom), 2, '.', ','); // -> 5,696.00
you can try this,it will work for you
number_format(0.00, 2)
A number of comments on this page have missed the fundamental point that the question is ill-formed. Floating point is a binary representation, designed for efficient calculations; it fundamentally has no notion of decimal digits of any sort.
So asking this:
How do I get "0.00" instead of "0" and still have the data type as a float?
Is like asking this:
How do I get "deux" instead of "zwei" and still have the language as English?
Whether you specify the input as "2", or "2.0", or "2.000000000", if you ask for a floating point value, what will be stored in memory is this (in IEEE 754 double-precision):
0100000000000000000000000000000000000000000000000000000000000000
If you convert to an integer, the value stored in memory is this (assuming a 64-bit system):
0000000000000000000000000000000000000000000000000000000000000010
(Note that "integer" in this context is not just a synonym for "whole number", it is a specific data type, with its own rules for how values should be represented in memory.)
By contrast, the string "2" would look like this:
00110010
And the string "2.00" would look like this:
00110010001011100011000000110000
(In a PHP program, there would actually be additional information in memory, such as an indicator of the type, but that's not really relevant here.)
So, the question can only be answered by rephrasing it as a conversion: given the input of a floating point number, how do I choose a string representation which has a fixed number of decimals.
As others have pointed out, the answer to that is to use number_format.
The question doesn't mention JSON, but several comments do, so I will also point out that PHP's json_encode function has an option JSON_PRESERVE_ZERO_FRACTION, which will format a floating point number that happens to be a whole number with a trailing ".0", for instance:
$example = ['int' => 2, 'float' => 2.0];
echo json_encode($example);
# => {"int":2,"float":2}
echo json_encode($example, JSON_PRESERVE_ZERO_FRACTION);
# => {"int":2,"float":2.0}
Again, note that this is a string representation of the value.
You can use round function
round("10.221",2);
Will return 10.22
You can use floatval()
floatval()
try this
$result = number_format($FloatNumber, 2);
You can use this simple function.
number_format ()
$num = 2214.56;
// default english notation
$english_format = number_format($num);
// 2,215
// French notation
$format_francais = number_format($num, 2, ',', ' ');
// 2 214,56
$num1 = 2234.5688;
// English notation with thousands separator
$english_format_number = number_format($num1,2);
// 2,234.57
// english notation without thousands separator
$english_format_number2 = number_format($num1, 2, '.', '');
// 2234.57
When we format any float value, that means we are changing its data type to string. So when we apply the formatting on any amount/float value then it will set with all possible notations like dot, comma, etc. For example
(float)0.00 => (string)'0.00',
(float)10000.56 => (string) '10,000.56'
(float)5000000.20=> (string) '5,000,000.20'
So, logically it's not possible to keep the float datatype after formatting.

Make dots between numbers in php

I would like to make dots between my total value.
If i have 425000 i would like it to show as 425.000
Is there a function in php that implodes dots for numbers or how can i do this then?
Use number_format for this:
$number = 425000;
echo number_format( $number, 0, '', '.' );
The above example means: format the number, using 0 decimal places, an empty string as the decimal point (as we're not using decimal places anyway), and use . as the thousands separator.
Unless of course I misunderstood your intent, and you want to format the number as a number with 3 decimal places:
$number = 425000;
echo number_format( $number, 3, '.', '' );
The above example means: format the number, using 3 decimal places, . as the decimal point (default), and an empty string as the thousands separator (defaults to ,).
If the default thousands separator is good enough for you, you can just use 1:
$number = 425000;
echo number_format( $number, 3 );
1) Mind you: number_format accepts either 1, 2 or 4 parameters, not 3.
I guess you're looking for the number_format function.

What would be the best way to detect if a float has a zero fraction value (e.g. 125.00) in PHP?

See, I want to write a function that takes a float number parameter and rounds the float to the nearest currency value (a float with two decimal places) but if the float parameter has a zero fraction (that is, all zeroes behind the decimal place) then it returns the float as an integer (or i.e. truncates the decimal part since they're all zeroes anyways.).
However, I'm finding that I can't figure out how to determine if if a fraction has a zero fraction. I don't know if there's a PHP function that already does this. I've looked. The best I can think of is to convert the float number into an integer by casting it first and then subtract the integer part from the float and then check if the difference equals to zero or not.
if($value == round($value))
{
//no decimal, go ahead and truncate.
}
This example compares the value to itself, rounded to 0 decimal places. If the value rounded is the same as the value, you've got no decimal fraction. Plain and simple.
A little trick with PHPs type juggling abilities
if ($a == (int) $a) {
// $a has a zero fraction value
}
I think the best way:
if ((string)$value == (int)$value){
...
}
Example:
$value = 2.22 * 100;
var_dump($value == (int)$value); // false - WRONG!
var_dump($value == round($value)); // false - WRONG!
var_dump((string)$value == (int)$value); // true - OK!
function whatyouneed($number) {
$decimals = 2;
printf("%.".($number == (int)($number) ? '0' : $decimals)."F", $number);
}
So basically it's either printf("%.2F") if you want 2 decimals and printf("%.2F") if you want none.
Well, the problem is that floats aren't exact. Read here if you're interested in finding out why. What I would do is decide on a level of accuracy, for example, 3 decimal places, and base exactness on that. To do that, you multiply it by 1000, cast it to an int, and then check if $your_number % 1000==0.
$mynumber = round($mynumber *1000);
if ($mynumber % 1000==0)
{ isInt() }
Just so you know, you don't have to write a function to do that, there's already one that exists:
$roundedFloat = (float)number_format("1234.1264", 2, ".", ""); // 1234.13
If you want to keep the trailing .00, just omit the float cast (although it will return a string):
$roundedFloatStr = number_format("1234.000", 2, ".", ""); // 1234.00

Categories