1 package net.sf.openrocket.util;
4 public class TextUtil {
7 * Return a string of the double value with suitable precision (5 digits).
8 * The string is the shortest representation of the value including the
11 * @param d the value to present.
12 * @return a representation with suitable precision.
14 public static final String doubleToString(double d) {
16 // Check for special cases
17 if (MathUtil.equals(d, 0))
23 if (Double.isInfinite(d)) {
31 final String sign = (d < 0) ? "-" : "";
32 double abs = Math.abs(d);
34 // Small and large values always in exponential notation
35 if (abs < 0.001 || abs >= 100000000) {
36 return sign + exponentialFormat(abs);
39 // Check whether decimal or exponential notation is shorter
41 String exp = exponentialFormat(abs);
42 String dec = decimalFormat(abs);
44 if (dec.length() <= exp.length())
52 * value must be positive and not zero!
54 private static String exponentialFormat(double value) {
62 while (value >= 10.0) {
67 return shortDecimal(value, 4) + "e" + exp;
72 * value must be positive and not zero!
74 private static String decimalFormat(double value) {
76 return "" + (int)(value + 0.5);
85 return shortDecimal(value, decimals);
92 * value must be positive!
94 private static String shortDecimal(double value, int decimals) {
96 int whole = (int)value;
99 // Calculate limit, return when remaining value less than this
102 for (int i=0; i<decimals; i++)
110 StringBuilder sb = new StringBuilder();
111 sb.append("" + whole);
115 for (int i = 0; i<decimals; i++) {
122 sb.append((char)('0' + whole));
125 return sb.toString();
130 return sb.toString();