Colon rounding without using Round or Truncate

I was asked the following question, and I did not know how to answer it. I was wondering if anyone could help:

Using C # rather than using any mathematical functions (Round () and Truncate () are not allowed) take the next double 3.009784654 and round it to 4 decimal places.

This was for an interview, not a class project or homework. The interviewer seemed to be trying to force me to use the mod, but I still could not figure out how to do this.

Thank!

+5
source share
6 answers

To truncate (since no rounding rules have been specified): multiply by 1e4, convert to int, divide by 1e4.

+7
source

, , , , , . , 3.0098. . - , , ( , , ..).

, , , , (int) (x * 10000 +.5) *. 0001. , ( ,.0001, 1), .5, . .5 , , , , /. . , , , , - .

(x * 10000 + 0x1p52-0x1p52) *. 0001. , , . , 53 , , 0x1p52 (2 52), 0x1p0 (2 0 1). 0x1p52, , . 0x1p52 , . , / , , - , . , , .

fmod string , , .

+2

10 ^ OfDigitsAfterComma, int float 10 ^...

double x = 3.009784654;
x =  ((double)((int)(x * 10000))) / 10000;
+1

, :

double number = 3.009784654;
double truncatedNumber = number - number % 0.0001;
+1

Answer using mod:

double d = 1.23456789;
int digitsToKeep = 2;
double divisor = Math.Pow(10, digitsToKeep * -1);
double rounded = d - (d % divisor);
0
source

It also rounds the number, if necessary.

public static double Round(double number, int digits)
{
    for (int i = 0; i < digits; i++)
        number *= 10;

    int whole = (int)number;
    double fraction = number - whole;

    if (fraction >= 0.5)
        whole++;

    number = whole;

    for (int i = 0; i < digits; i++)
        number /= 10.0;

    return number;
}
0
source

All Articles