November 26, 201411 yr Hi Gang, Probably really simple but here's what's driving me round in circles. What I want is to display a number to 2 decimal places with the option of floating one 0 if required. So here's what I got, none of which do exactly what I need. // Number stored is 1.25 $number = 1.25; echo (float)$number; // makes 1.25 ideal! echo number_format($number, 1, '.', ''); // makes 1.2 - not good. // Number stored is 2.50 $number = 2.50; echo (float)$number; // makes 2.5 Ideal! echo number_format($number, 1, '.', ''); // makes 2.5 ideal! // Number stored is 1.00 $number = 1.00; echo (float)$number; // makes 1 - not good echo number_format($number, 1, '.', ''); // makes 1.0 ideal! What's glaringly obvious that I'm missing here? Thanks
November 26, 201411 yr Author Hi! Have you tried: number_format($number, 2, '.', ''); Yes but then it makes 1.0 become 1.00. To clarify I want the following to display; 1.00 display as 1.0 1.25 display as 1.25 2.50 display as 2.5 Thanks though
November 26, 201411 yr Author Yeah I was looking into breaking the number apart and then fiddling with the decimal section however I really wondered if there was an out the box number format of some description already built into php. Thanks Nock, this is probably the route for now.
November 27, 201411 yr Author Thanks Nock, made a little function for anyone else wanting to do this, aka the nockNumber function nockNumber($var) { $rumble = explode(".", $var); if(substr($rumble[1], -1)==0) { $var = $rumble[0] . "." . substr($rumble[1], 0, 1); } return $var; }
Create an account or sign in to comment