回答編集履歴

1

有効数頭3桁というのを見落としていた

2022/11/26 10:27

投稿

KOZ6.0
KOZ6.0

スコア2622

test CHANGED
@@ -1,25 +1,65 @@
1
1
  指数表記にこだわらなければ、いかようにでも作れると思いますが・・・
2
2
  ```CSharp
3
+ using System;
3
- static void Main(string[] args) {
4
+ using System.Collections.Generic;
5
+ using System.Linq;
4
6
 
7
+ internal static class Program
8
+ {
5
- Console.WriteLine(999999d.ToReadableString());
9
+ static void Main(string[] args) {
10
+ print(999999d);
6
- Console.WriteLine(1000000d.ToReadableString());
11
+ print(1000000d);
12
+ print(12d);
13
+ print(1234d);
14
+ print(123456d);
15
+ print(12345678d);
7
- Console.ReadKey();
16
+ Console.ReadKey();
17
+ }
18
+
19
+ static void print(double d) {
20
+ Console.WriteLine($"{d} => {d.ToReadableString()}");
21
+ }
22
+
23
+ public static string ToReadableString(this double d) {
24
+ var sign = Math.Sign(d);
25
+ var value = Math.Abs(d);
26
+ int i;
27
+ for (i = 0; i < suffixes.Length - 1; i++) {
28
+ if (value < 1000) {
29
+ break;
30
+ }
31
+ value = Math.Truncate(value / 10) / 100;
32
+ }
33
+ var str = (value * 1000).ToString();
34
+ if (str.Length > 3) {
35
+ str = str.Substring(0, 3) + new string('0', str.Length - 3);
36
+ }
37
+ value = double.Parse(str) / 1000;
38
+ return (sign * value).ToString() + suffixes[i];
39
+ }
40
+
41
+ private static string[] _suffixes;
42
+ private static string[] suffixes {
43
+ get {
44
+ if (_suffixes == null) {
45
+ const string AtoZ = " ABCDEFGHIJKLMNOPQRSTUVWXYZ";
46
+ var list = new List<string>();
47
+ list.Add("");
48
+ list.Add("k");
49
+ list.Add("m");
50
+ list.Add("b");
51
+ list.Add("t");
52
+ for (var x = 0; x < AtoZ.Length; x++)
53
+ for (var y = 1; y < AtoZ.Length; y++) {
54
+ var str = string.Format("{0}{1}", AtoZ[x], AtoZ[y]).Trim();
55
+ list.Add(str);
56
+ }
57
+ _suffixes = list.Take(308).ToArray();
58
+ }
59
+ return _suffixes;
60
+ }
61
+ }
8
62
  }
63
+ ```
64
+ ところで、頭3桁のみ有効桁にするのであれば、999999 → 999k になるのでは?
9
65
 
10
- static readonly string[] suffix = new string[] { "", "K", "M", "G", "T" };
11
-
12
- public static string ToReadableString(this double d) {
13
- var sign = Math.Sign(d);
14
- var value = Math.Abs(d);
15
- int i;
16
- for (i = 0; i < suffix.Length - 1; i++) {
17
- if (value < 1000) {
18
- break;
19
- }
20
- value = Math.Truncate(value / 100) / 10;
21
- }
22
- return (sign * value).ToString("##0.0") + suffix[i];
23
- }
24
-
25
- ```