1 | using System;
|
---|
2 | using System.Collections.Generic;
|
---|
3 | using System.Linq;
|
---|
4 | using System.Text;
|
---|
5 | using System.Diagnostics;
|
---|
6 |
|
---|
7 | namespace Microsoft.Research.DynamicDataDisplay.Charts
|
---|
8 | {
|
---|
9 | internal static class RoundingHelper
|
---|
10 | {
|
---|
11 | internal static int GetDifferenceLog(double min, double max)
|
---|
12 | {
|
---|
13 | return (int)Math.Round(Math.Log10(Math.Abs(max - min)));
|
---|
14 | }
|
---|
15 |
|
---|
16 | internal static double Round(double number, int rem)
|
---|
17 | {
|
---|
18 | if (rem <= 0)
|
---|
19 | {
|
---|
20 | rem = MathHelper.Clamp(-rem, 0, 15);
|
---|
21 | return Math.Round(number, rem);
|
---|
22 | }
|
---|
23 | else
|
---|
24 | {
|
---|
25 | double pow = Math.Pow(10, rem - 1);
|
---|
26 | double val = pow * Math.Round(number / Math.Pow(10, rem - 1));
|
---|
27 | return val;
|
---|
28 | }
|
---|
29 | }
|
---|
30 |
|
---|
31 | internal static double Round(double value, Range<double> range)
|
---|
32 | {
|
---|
33 | int log = GetDifferenceLog(range.Min, range.Max);
|
---|
34 |
|
---|
35 | return Round(value, log);
|
---|
36 | }
|
---|
37 |
|
---|
38 | internal static RoundingInfo CreateRoundedRange(double min, double max)
|
---|
39 | {
|
---|
40 | double delta = max - min;
|
---|
41 |
|
---|
42 | if (delta == 0)
|
---|
43 | return new RoundingInfo { Min = min, Max = max, Log = 0 };
|
---|
44 |
|
---|
45 | int log = (int)Math.Round(Math.Log10(Math.Abs(delta))) + 1;
|
---|
46 |
|
---|
47 | double newMin = Round(min, log);
|
---|
48 | double newMax = Round(max, log);
|
---|
49 | if (newMin == newMax)
|
---|
50 | {
|
---|
51 | log--;
|
---|
52 | newMin = Round(min, log);
|
---|
53 | newMax = Round(max, log);
|
---|
54 | }
|
---|
55 |
|
---|
56 | return new RoundingInfo { Min = newMin, Max = newMax, Log = log };
|
---|
57 | }
|
---|
58 | }
|
---|
59 |
|
---|
60 | [DebuggerDisplay("{Min} - {Max}, Log = {Log}")]
|
---|
61 | internal sealed class RoundingInfo
|
---|
62 | {
|
---|
63 | public double Min { get; set; }
|
---|
64 | public double Max { get; set; }
|
---|
65 | public int Log { get; set; }
|
---|
66 | }
|
---|
67 | }
|
---|