1 package org.simantics.maps.sg;
3 import java.util.Locale;
6 * @author Tuukka Lehtonen
10 private static final transient double EPSILON = 0.01;
12 private static final transient double TRIM_THRESHOLD_MAX_VALUE = Math.pow(10, 4);
14 private static final transient String[] SI_UNIT_LARGE_PREFIXES = {
15 "k", "M", "G", "T", "P", "E", "Z", "Y"
18 public static enum FormatMode {
23 public static String formatValue(double value, int max, boolean removeTrailingZeros, FormatMode formatMode) {
24 return formatValue(value, max, removeTrailingZeros, formatMode, TRIM_THRESHOLD_MAX_VALUE);
27 public static String formatValue(double value, int max, boolean removeTrailingZeros, FormatMode formatMode, double trimThresholdMaxValue) {
28 return formatValue(value, max, removeTrailingZeros, formatMode, trimThresholdMaxValue, true);
31 public static String formatValue(double value, int max, boolean removeTrailingZeros, FormatMode formatMode, double trimThresholdMaxValue, boolean trimLargeValues) {
32 //System.out.println("formatValue(" + value + ", " + max + ", " + removeTrailingZeros + ", " + formatMode + ", " + trimThresholdMaxValue + ", " + trimLargeValues + ")");
33 int allowedDecimals = max;
34 if (formatMode == FormatMode.LIMIT_DIGITS) {
35 int magnitude = (int) Math.ceil(Math.log10(Math.abs(value)));
36 //System.out.println("magnitude(" + value + "): " + magnitude);
37 allowedDecimals -= Math.abs(magnitude);
38 if (allowedDecimals < 0)
40 //System.out.println("allowedDecimals: " + allowedDecimals);
43 String valueStr = String.format(Locale.US, "%." + allowedDecimals + "f", value);
44 if (allowedDecimals > 0) {
45 if (removeTrailingZeros) {
46 for (int trunc = valueStr.length() - 1; trunc > 0; --trunc) {
47 char ch = valueStr.charAt(trunc);
49 valueStr = valueStr.substring(0, trunc);
53 valueStr = valueStr.substring(0, trunc + 1);
58 if (Math.abs(value) + EPSILON > trimThresholdMaxValue) {
59 // Cut anything beyond a possible decimal dot out since they
60 // should not show anyway. This is a complete hack that tries to
61 // circumvent floating-point inaccuracy problems.
62 int dotIndex = valueStr.lastIndexOf('.');
64 valueStr = valueStr.substring(0, dotIndex);
69 if (valueStr.equals("-0"))
72 if (trimLargeValues) {
73 double trimValue = value;
74 if (Math.abs(value) + EPSILON >= trimThresholdMaxValue) {
75 for (int i = 0; Math.abs(trimValue) + EPSILON >= trimThresholdMaxValue; ++i) {
76 double trim = trimValue / 1000;
77 if (Math.abs(trim) - EPSILON < trimThresholdMaxValue) {
78 valueStr = valueStr.substring(0, valueStr.length() - (i + 1) * 3);
79 valueStr += SI_UNIT_LARGE_PREFIXES[i];
87 //System.out.println("formatted result: " + valueStr);