Maarten Wolfsen
Maarten Wolfsen

Reputation: 1733

Always round up on first decimal

I want my variable's first decimal to always be rounded up. For example:

9.66 goes to 9.7
9.55 goes to 9.6
9.51 goes to 9.6
9.00000001 goes to 9.1

How do I do this?

Upvotes: 1

Views: 468

Answers (5)

Murad Hasan
Murad Hasan

Reputation: 9583

Use this: online test

You can use this technique. Just explode the given number / string, get the number which is next value / digit of the .. after getting this you need to increment that value and check if the value is greater than 9 or nor, if then divide that and add the carry to the first portion of the main number.

$var = '9.96';
$ar = explode(".", $var);

$nxt = substr($ar[1], 0, 1) + 1;

if($nxt > 9){
    $tmp = (string) $nxt;
    $num = floatval(($ar[0] + $tmp[0]).".".$tmp[1]);
}   
else
    $num = floatval($ar[0].".".$nxt);

var_dump($num); // float(10)

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234715

I'm not a php programmer so will have to answer in "steps". The problem you have is the edge case where you have a number with exactly one decimal. (e.g. 9.5)

Here's how you could do it:

  1. Multiply your number by 10.
  2. If that's an integer, then return the original number (that's the edge case), else continue as follows:
  3. Add 0.5
  4. Round that in the normal way to an integer (i.e. "a.5" rounds up).
  5. Divide the result by 10.

For step (2), sniffing around the php documentation reveals a function bool is_int ( mixed $var ) to test for an integer.

Upvotes: 1

Victor Smirnov
Victor Smirnov

Reputation: 3780

I made couple tests and suggest the following answer with test cases

<?php

echo '9.66 (expected 9.7) => '.myRound(9.66).PHP_EOL;
echo '9.55 (expected 9.6) => '.myRound(9.55).PHP_EOL;
echo '9.51 (expected 9.6) => '.myRound(9.51).PHP_EOL;
echo '9.00000001 (expected 9.1) => '.myRound(9.00000001).PHP_EOL;
echo '9.9 (expected ??) => '.myRound(9.9).PHP_EOL;
echo '9.91 (expected ??) => '.myRound(9.91).PHP_EOL;

function myRound($value)
{
    return ceil($value*10)/10;
}

Upvotes: 1

jotik
jotik

Reputation: 17900

Use round() with an optional precision and round type arguments, e.g.:

round($value, 1, PHP_ROUND_HALF_UP)

The optional second argument to round() is the precision argument and it specifies the number of decimal digits to round to. The third optional argument specifies the rounding mode. See the PHP manual for round for details.

Using round() does not always round up, even when using PHP_ROUND_HALF_UP (e.g. 9.00001 is not rounded to 9.1). You could instead try to use multiplication, ceil() and division:

ceil($value * 10.0) / 10.0

Since these are floating-point values, you might not get exact results.

Upvotes: 2

Elzo Valugi
Elzo Valugi

Reputation: 27866

You will need a custom ceil() function, your requirements cannot be satisfied by the default function or by the round.

Upvotes: 0

Related Questions