开发者

Round Up/down with Rule Using Math Function only?

开发者 https://www.devze.com 2023-03-10 03:29 出处:网络
Some Math people please help, I want to convert using only Math. Function. (Pow, Floor......etc) with only single statementas possile, not using if else to check if the 5fifth digits after decimals fr

Some Math people please help, I want to convert using only Math. Function. (Pow, Floor......etc) with only single statement as possile, not using if else to check if the 5fifth digits after decimals from 1-4 or 6-9 .

  • i want to convert 5 digits after decimal to 5 digits after decimal with the following rules , alway 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 
开发者_JS百科

I Came up with answer for Rule 1, but it need to 2 statement, I wonder if it can be done with only 1 statement

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

Thanks


For rule #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 #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


Remember how you round (to an integer):

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

So, now salt it with some multiplications with powers of 10, some adding of .5 and pepper it with some division by powers of 10 and you are set.

0

精彩评论

暂无评论...
验证码 换一张
取 消