Thread Runden und kleinste Einheit (13 answers)
Opened by esskar at 2007-06-13 16:23

esskar
 2007-06-13 17:29
#77499 #77499
User since
2003-08-04
7321 Artikel
ModeratorIn

user image
hier mal mein c# implementierung
Code: (dl )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public static decimal ToUnit(decimal number, decimal unit, MidpointRounding mode)
{
if (unit > 1m) unit = 1m;

string unitStr = unit.ToString();
int decimals = 0;

string separator = ThreadHelper.CurrentNumberFormat.NumberDecimalSeparator;
int idx = unitStr.IndexOf(separator);
if (idx >= 0)
{
bool nonZero = false;

unitStr = unitStr.Substring(idx + separator.Length);
foreach (char c in unitStr)
{
if (c == '0' && nonZero) break;
if (c != '0') nonZero = true;
decimals++;
}
}

number = decimal.Round(number, decimals, mode);

decimal i = decimal.ToInt32(number);
decimal f = (decimal)Math.Pow(10d, decimals);
decimal d = (number - i) * f;
decimal u = unit * f;

number = i + (d - d % u) / f;

return number;
}


kommt mir aber nur auf den algorithmus und nicht die sprache an!

View full thread Runden und kleinste Einheit