DEV Community

Mohammed Samgan Khan
Mohammed Samgan Khan

Posted on • Edited on • Originally published at dev.to

2 1

function to round up a float number to next point five like 3.3 to 3.5, 3.8 to 4

If you are from the shipping industry you face this problem a lot of time where you charge per 0.5 kg. In this kind of case, you need to make the weight from float to round up.

here is a php function to achieve that.

<?php
/**
* * Problem Statement:
* * passing a floating point number to a function, the function will round the number to
* * the nearest point five and return the result.
*
* * Example:
* * roundUpToNextFive(3.7) // returns 4.0
* * roundUpToNextFive(3.3) // returns 3.5
* * roundUpToNextFive(3.8) // returns 4.0
* * roundUpToNextFive(1.2) // returns 1.5
*/
/**
* Rounds the given number up to the next five.
*
* @param float $number
* @return float
*/
function roundUpToNextFive(float $number)
{
printf("The number is %.2f \n", $number);
$decimalPart = $number - floor($number);
return ($decimalPart > 0.50 ? ceil($decimalPart) : (ceil($decimalPart) / 2)) + floor($number);
}
printf("The next closest five is %.2f \n", roundUpToNextFive(5.33));

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs