MCPcopy Create free account
hub / github.com/google/truth / formatNumericValue

Method formatNumericValue

core/src/main/java/com/google/common/truth/Fact.java:100–135  ·  view source on GitHub ↗

Formats the given numeric value as a string with delimiting commas. Note: only Long, Integer, Float, Double and BigDecimal are supported.

(@Nullable Number value)

Source from the content-addressed store, hash-verified

98 * BigDecimal} are supported.
99 */
100 static String formatNumericValue(@Nullable Number value) {
101 if (value == null) {
102 return "null";
103 }
104 // the value must be a numeric type
105 checkArgument(
106 value instanceof Long
107 || value instanceof Integer
108 || value instanceof Float
109 || value instanceof Double
110 || value instanceof BigDecimal,
111 "Value (%s) must be either a Long, Integer, Float, Double, or BigDecimal.",
112 value);
113
114 // DecimalFormat is not available on all platforms, so we do the formatting manually.
115
116 if (!(value instanceof BigDecimal) && isInfiniteOrNaN(value.doubleValue())) {
117 return value.toString();
118 }
119 String stringValue =
120 value instanceof Double
121 ? doubleToString((double) value)
122 : value instanceof Float //
123 ? floatToString((float) value)
124 : value.toString();
125 if (stringValue.contains("E")) {
126 return stringValue;
127 }
128 int decimalIndex = stringValue.indexOf('.');
129 if (decimalIndex == -1) {
130 return formatWholeNumericValue(stringValue);
131 }
132 String wholeNumbers = stringValue.substring(0, decimalIndex);
133 String decimal = stringValue.substring(decimalIndex);
134 return formatWholeNumericValue(wholeNumbers) + decimal;
135 }
136
137 private static boolean isInfiniteOrNaN(double d) {
138 return Double.isInfinite(d) || Double.isNaN(d);

Calls 6

isInfiniteOrNaNMethod · 0.95
containsMethod · 0.65
toStringMethod · 0.45
doubleToStringMethod · 0.45
floatToStringMethod · 0.45