Round Up / down using a rule using only a math function?

Some math people, please help, I want to convert using only Math. Function. (Pow, Floor ...... etc.) With a single expression as possible, not using if you still need to check if the 5th digits after decimal places are from 1-4 or 6-9.

  • I want to convert 5 digits after a decimal to 5 digits after a decimal with the following rules: always 5 and 0 at the end.

Rule 1:

double number1 = 1.2345* 
if( * from 1 to 4)
   number1 ==> 1.23455 
if ( * from 6 to 9)
  number1  ==> 1.23460 

Rule 2:

double number2 = 1.2345* 
if( * from 1 to 4)
   number2 ==> 1.23450 

if ( * from 6 to 9)
  number2  ==> 1.23455 

I came up with an answer for rule 1, but I need to do it 2, I wonder if this can be done with just one statement

number1 = Math.Floor((number1 + 0.00005) * 20000) / 20000 - 0.00005;
number1 = Math.Floor((number1 + 0.00005) * 20000) / 20000 ;

thank

+3
source share
2 answers

For rule number 1:

var y = (int)((x - 0.00001) * 20000) / 20000.0 + 0.00005;

Result:

1.23450 => 1.23450
1.23451 => 1.23455
1.23452 => 1.23455
1.23453 => 1.23455
1.23454 => 1.23455
1.23455 => 1.23455
1.23456 => 1.23460
1.23457 => 1.23460
1.23458 => 1.23460
1.23459 => 1.23460
1.23460 => 1.23460

For rule number 2:

var y = (int)(x * 20000) / 20000.0;

Result:

1.23450 => 1.23450
1.23451 => 1.23450
1.23452 => 1.23450
1.23453 => 1.23450
1.23454 => 1.23450
1.23455 => 1.23455
1.23456 => 1.23455
1.23457 => 1.23455
1.23458 => 1.23455
1.23459 => 1.23455
+3

, ( ):

round (a) = floor (a + .5)

, 10, .5 10 .

+2

All Articles