1 package net.sf.openrocket.util;
4 public class TextUtil {
5 private static final char[] HEX = {
6 '0', '1', '2', '3', '4', '5', '6', '7',
7 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
12 * Return the bytes formatted as a hexadecimal string. The length of the
13 * string will be twice the number of bytes, with no spacing between the bytes
14 * and lowercase letters utilized.
16 * @param bytes the bytes to convert.
17 * @return the bytes in hexadecimal notation.
19 public static final String hexString(byte[] bytes) {
20 StringBuilder sb = new StringBuilder(bytes.length * 2);
21 for (byte b : bytes) {
22 sb.append(HEX[(b >>> 4) & 0xF]);
23 sb.append(HEX[b & 0xF]);
29 * Return a string of the double value with suitable precision (5 digits).
30 * The string is the shortest representation of the value including the
33 * @param d the value to present.
34 * @return a representation with suitable precision.
36 public static final String doubleToString(double d) {
38 // Check for special cases
39 if (MathUtil.equals(d, 0))
45 if (Double.isInfinite(d)) {
53 final String sign = (d < 0) ? "-" : "";
54 double abs = Math.abs(d);
56 // Small and large values always in exponential notation
57 if (abs < 0.001 || abs >= 100000000) {
58 return sign + exponentialFormat(abs);
61 // Check whether decimal or exponential notation is shorter
63 String exp = exponentialFormat(abs);
64 String dec = decimalFormat(abs);
66 if (dec.length() <= exp.length())
74 * value must be positive and not zero!
76 private static String exponentialFormat(double value) {
84 while (value >= 10.0) {
89 return shortDecimal(value, 4) + "e" + exp;
94 * value must be positive and not zero!
96 private static String decimalFormat(double value) {
98 return "" + (int) (value + 0.5);
107 return shortDecimal(value, decimals);
114 * value must be positive!
116 private static String shortDecimal(double value, int decimals) {
118 // Calculate rounding and limit values (rounding slightly smaller)
121 for (int i = 0; i < decimals; i++) {
127 value = (Math.rint(value * rounding) + 0.1) / rounding;
130 int whole = (int) value;
138 StringBuilder sb = new StringBuilder();
139 sb.append("" + whole);
143 for (int i = 0; i < decimals; i++) {
148 sb.append((char) ('0' + whole));
151 return sb.toString();
156 return sb.toString();
160 public static String htmlEncode(String s) {
161 s = s.replace("&", "&");
162 s = s.replace("\"", """);
163 s = s.replace("<", "<");
164 s = s.replace(">", ">");