Reputation: 529
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.
Upvotes: 1
Views: 130
Reputation: 12797
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);
Upvotes: 2
Reputation: 377
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?
Upvotes: 1
Reputation: 120450
var left = 12345;
var right = 12345678;
var total = left + (right / Math.Pow(10, Math.Floor(Math.Log10(right)) + 1));
Upvotes: 4
Reputation: 6373
A very quick and dirty approach, with no error checking at all
var total = Double.Parse(string.Concat(left, ",", right));
Upvotes: 3