1 package com.github.mygreen.cellformatter.number;
2
3 import java.math.RoundingMode;
4 import java.text.DecimalFormat;
5
6
7
8
9
10
11
12 public class ExponentNumber extends DecimalNumber {
13
14
15
16
17
18
19 private String exponentPart;
20
21
22
23
24
25 private int exponentSign;
26
27
28
29
30
31
32 public ExponentNumber(final double value, final int decimalScale) {
33 super(value, decimalScale);
34 }
35
36 @Override
37 protected void init() {
38
39 if(isZero()) {
40 this.integerPart = "";
41 this.decimalPart = "";
42 this.exponentPart = "0";
43 this.exponentSign = 1;
44 return;
45 }
46
47 final StringBuilder sb = new StringBuilder();
48 sb.append("#");
49
50
51 sb.append(".");
52
53
54 for(int i=0; i < getScale(); i++) {
55 sb.append("#");
56 }
57
58
59 sb.append("E0");
60
61 final DecimalFormat format = new DecimalFormat(sb.toString());
62 format.setRoundingMode(RoundingMode.HALF_UP);
63 String str = format.format(Math.abs(getValue()));
64
65
66 final int exponentIdx = str.indexOf("E");
67 final String numberPart = str.substring(0, exponentIdx);
68 final String exponentPart = str.substring(exponentIdx+1);
69
70 setupIntegerAndDecimalPart(numberPart);
71
72
73 if(exponentPart.startsWith("-")) {
74
75 this.exponentSign = -1;
76 this.exponentPart = exponentPart.substring(1);
77 } else {
78 this.exponentSign = 1;
79 this.exponentPart = exponentPart;
80 }
81
82 }
83
84
85
86
87
88
89 public boolean isExponentPositive() {
90 return exponentSign >= 0;
91 }
92
93
94
95
96
97
98 public boolean isExponentNegative() {
99 return exponentSign < 0;
100 }
101
102
103
104
105
106 public String getExponentPart() {
107 return exponentPart;
108 }
109
110
111
112
113
114
115 public String getExponentPart(final int digit) {
116
117 final int length = exponentPart.length();
118 if(length < digit || digit <= 0) {
119 return "";
120 }
121
122 return String.valueOf(exponentPart.charAt(length - digit));
123
124 }
125
126
127
128
129
130
131 public String getExponentPartAfter(final int digit) {
132
133 final int length = exponentPart.length();
134 if(length < digit || digit <= 0) {
135 return "";
136 }
137
138 return exponentPart.substring(0, length - digit + 1);
139
140 }
141
142 @Override
143 public String toString() {
144
145 StringBuilder sb = new StringBuilder();
146 sb.append(super.toString());
147
148 sb.append("E");
149 if(isExponentPositive()) {
150 sb.append("+");
151 } else {
152 sb.append("-");
153 }
154
155 sb.append(getExponentPart());
156
157 return sb.toString();
158 }
159
160 }