user1873073
user1873073

Reputation: 3670

Is there a way to round or ceil BigInteger?

I have a BigIntiger, say 1234567890 and I'm looking for the fastest possible way to turn that into something like one of these:

Upvotes: 5

Views: 3078

Answers (2)

Lei Yang
Lei Yang

Reputation: 4335

Another way is to split the string. Although there may be performance issue, the result is OK.

    //n=1, 2, 8 to check for your example
    static long F(long num, int n)
    {
        string all = num.ToString();
        long headn = Convert.ToInt64(all.Substring(0, n)) + 1;
        return (long)(headn * Math.Pow(10, all.Length - n));
    }

Upvotes: 0

Alexei Levenkov
Alexei Levenkov

Reputation: 100545

I don't think there is built-in way of doing so.

The easiest way to get "no remainder" is to just decrease value by remainder:

"Rounded" to not give remainder for 13:

  var x = new BigInteger(123456);
  var roundedTo13 = x - (x % 13);

Or to 100:

  var roundedTo100 = x - (x % 100);
  Console.WriteLine(roundedTo100);

If you need rounding in more traditional sense - check if remainder is greater than value you want to round by and sign of number you want to round. If value of remainder (x % 100) is greater than half you'd need to add/substract 100.

Upvotes: 3

Related Questions