0

Unexpected result in php when carrying out simple math to convert from a unit in meters to mm.

$width  = (float)1.0050;
echo 'Width: '.$width.'m';
$width = (int)($width*1000);
echo 'Width:'. $width . 'mm';

This is returning

Width: 1.005m
Width:1004mm

When expected result would be 1005mm.

Any help is appreciated.

RossW
  • 149
  • 7
  • 3
    Possible duplicate of [PHP typecasting float->int](http://stackoverflow.com/questions/2055469/php-typecasting-float-int) – Ruslan Osmanov Dec 09 '16 at 09:53
  • 1
    You may read this: http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html and this : http://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate – rap-2-h Dec 09 '16 at 09:54

2 Answers2

1

internally php represent $width as float with value: 1.0049999999999999 the casting operation simply strip the number after the coma, the you receive 1004.

Use round instead:

round($width * 1000);
m47730
  • 2,061
  • 2
  • 24
  • 30
0

As far I know, (float)anyNumberWithDecimals does not convert METRIC units, in any program language. It makes a cast, to specify what type of variable is.

tec
  • 999
  • 3
  • 18
  • 40