-2

I'm trying to do an activity where I need do put a number in cm, and the program has to return it with km, m, and cm.

An example: 270004 cm = 2km, 700m, 4cm // 100cm = 0km, 1m, 0cm.

I have done this code, but, sometimes I get negative numbers, and sometimes I get strange numbers.

Maybe is why I use the PHP_ROUND_HALF_UP??

What can I do to solve it?

//I have an HTML form to introduce the number value
$num = 123456789;

$km = $num/1000;
$km = round($km, 0, PHP_ROUND_HALF_UP);
echo "km: ".$km."<br>";

$subtraction = ($km * 1000) - $num;
$m = $subtraction / 100;
$m = round($m, 0, PHP_ROUND_HALF_UP);

echo "m: ".$m."<br>";

$subtraction2 = ($m * 100) - $subtraction;
$cm = $subtraction2;

echo "cm: ".$cm."<br>";           
Crisoforo Gaspar
  • 3,740
  • 2
  • 21
  • 27
blaclotus
  • 45
  • 2
  • 3
  • 5
  • Can you share the input numbers and the strange number results? – Jay Blanchard Oct 08 '14 at 21:02
  • What is `$resta=($km*1000)-$num;` supposed to do? That can easily give you a negative, especially if you have rounded $km up rather than down – Mark Baker Oct 08 '14 at 21:02
  • For example, with number 123456789 i get: km: 123457 m: 2 cm: -11, and I want to get: 1234 km, 567 m y 89 cm. – blaclotus Oct 08 '14 at 21:06
  • Recommended reading: http://stackoverflow.com/questions/17524673/understanding-the-modulus-operator – Sammitch Oct 08 '14 at 21:12
  • You shouldn't be rounding; you should be using floor. Also, what units is $num in? Centimeters? Then your first operation should have been $km=$num/(1000 * 100); – Kai Oct 08 '14 at 21:13

2 Answers2

7

Honestly, your code seems to be a bit over complicated :P Ever heard of modulo division? Comes in handy in here!

<?php

$x = 123456789323; // centimeters

$km  = floor($x / 100000); // amount of "full" kilometers
$rkm = $x % 100000; // rest

$m  = floor($rkm / 100); // amount of "full" meters"
$cm = $rkm % 100; // rest

echo $x . ' cm = ' . $km . ' kilometers ' . $m . ' meters and ' . $cm . 'centimeters' . PHP_EOL;
paranoid
  • 535
  • 2
  • 11
2
$cm = 234459891345;

echo sprintf('km: %02d m: %02d cm: %02d', ($cm/100000),($cm/100%100), $cm%100);
Steve
  • 20,703
  • 5
  • 41
  • 67