开发者

PHP long decimal number issue

开发者 https://www.devze.com 2023-03-10 10:57 出处:网络
Im parsing xml开发者_如何转开发 using php and one of my variables receive a long decimal value.

Im parsing xml开发者_如何转开发 using php and one of my variables receive a long decimal value.

$ctr = 0.00529440333938;

But I need to make this number as 0.52%, so I tried multiplying by 100 and forcing just 2 decimals.

$real_ctr = $ctr * 100;
echo number_format($real_ctr, 2) . "%";

I get as result 0.00% instead 0f 0.52%

And then I tried adding 1 just for testing purpose

$real_ctr = $ctr + 1;

and I get as result 0.005294403339381. It adds 1 at the end.

Any suggestions how can I get around this issue?


this is working for me:

$ctr = 0.00529440333938; 

$real_ctr = (double)$ctr * 100; 
$real_ctr = number_format($real_ctr, 2, ".", "") . "%";
$real_ctr = $ctr + 1;

and use number_format($real_ctr, 2, ".", ""), if you don't live in UK.


It seams $ctr what you get from the XML parser is a string. Use:

$ctr = floatval($ctr); // or (double)$ctr; or (float)$ctr;

to make sure your variable is a float.


The nature of floating-point and double type variables is that they are not able to be relied upon for last-digit accuracy. Check out the manual: http://php.net/manual/en/language.types.float.php

It is important to understand floats before you use them - if you're doing any kind of financial calculations, floats will give you unexpected results because of their inherent imprecision. You're better off sticking to doubles if you need precise results, especially if you're working with anything related to money.

So, make sure you're using the type of number you're expecting. You're running into the issue where your number is being turned into a float/double because of PHP's loose typing. Check out the docs on type-juggling: http://www.php.net/manual/en/language.types.type-juggling.php, there may be some useful information there.

Basically, you'll need to ensure that your numbers are staying as integers through your calculations, you need to prevent PHP from "deciding' the type for you. Look in to intval, or the BC precision math functions, if you need to get that deep: http://www.php.net/manual/en/ref.bc.php


It's being read as a string. Are you literally setting it equal to 0.00529440333938, or are you setting it equal to something that you think is equal to 0.00529440333938? Try this after the assignment statement and see if it works:

$ctr = floatval($ctr);
0

精彩评论

暂无评论...
验证码 换一张
取 消