1

I need to be able to attach an integer number to another integer as a decimal part, for example:

For numbers 12345 and 12345678 I would want to get: 12345,12345678

Note: The numbers' length is variable.

I have tried casting numbers to string to measure their length and then divide them accordingly but there must be a more efficient and fast way than this.

Doug Peters
  • 529
  • 2
  • 8
  • 17
  • are you sure that your current approach is too slow for your case? Or this question is just about interest of what are the ways to accomplish the task? – Alexander Manekovskiy Jun 08 '14 at 17:06
  • @AlexanderManekovskiy I am performing this operation to a few million numerical pairs and it takes quite a while, I suppose it could go faster. – Doug Peters Jun 08 '14 at 17:09

4 Answers4

4
var left = 12345;
var right = 12345678;
var total = left + (right / Math.Pow(10, Math.Floor(Math.Log10(right)) + 1));
spender
  • 117,338
  • 33
  • 229
  • 351
3

A very quick and dirty approach, with no error checking at all

var total = Double.Parse(string.Concat(left, ",", right));
Code Uniquely
  • 6,356
  • 4
  • 30
  • 40
2

Based on https://stackoverflow.com/a/2506541/1803777, more performance can be obtained without usage of logarithm function.

public static decimal GetDivider(int i)
{
    if (i < 10) return 10m;
    if (i < 100) return 100m;
    if (i < 1000) return 1000m;
    if (i < 10000) return 10000m;
    if (i < 100000) return 100000m;
    if (i < 1000000) return 1000000m;
    if (i < 10000000) return 10000000m;
    if (i < 100000000) return 100000000m;
    if (i < 1000000000) return 1000000000m;
    throw new ArgumentOutOfRangeException();
}

int a = 12345;
int b = 12345678;
decimal x = a + b / GetDivider(b);
Community
  • 1
  • 1
Ulugbek Umirov
  • 12,719
  • 3
  • 23
  • 31
  • How does this scale so as to include BigInteger ranges as well? I wouldn't want to write a few hundred `if` lines. Any ideas? – Doug Peters Jun 08 '14 at 18:26
  • @DougPeters What type do you plan to use for that number of digits after the decimal? Technically you can make while loop to calculate the divider. – Ulugbek Umirov Jun 08 '14 at 18:41
1

try counting using the following:

Math.Floor(Math.Log10(n) + 1);

then continue just as you stated.

Source: How can I get a count of the total number of digits in a number?

Community
  • 1
  • 1
vvvlad
  • 378
  • 2
  • 13