feat(string-formatter): enhance toString logic for doubles and floats
ci/woodpecker/push/woodpecker Pipeline was successful Details

This commit is contained in:
Johannes Frohnmeyer 2023-08-20 14:10:05 +02:00
parent 2ae6900447
commit 0ca5b4f323
Signed by: Johannes
GPG Key ID: E76429612C2929F4
1 changed files with 20 additions and 7 deletions

View File

@ -6,13 +6,26 @@ import java.util.function.Function;
public class StringFormatter {
public static String toString(Object o) {
if (o == null) return "null";
else if (o instanceof Double d) {
if (d % 1.0 == 0) return String.format(Locale.US, "%.0f", d);
else if (d > 1) return String.format(Locale.US, "%.4f", d);
else return String.format(Locale.US, "%s", d);
} else if (o instanceof Throwable t) {
return toString(t, Objects::toString);
} else return o.toString();
else if (o instanceof Double d) return toString(d);
else if (o instanceof Float f) return toString(f);
else if (o instanceof Throwable t) return toString(t, Objects::toString);
else return o.toString();
}
public static String toString(double d) {
double abs = Math.abs(d);
if (abs % 1.0 == 0) return String.format(Locale.US, "%.0f", d);
else if (abs >= 1000) return String.format(Locale.US, "%.0f", d);
else if (abs >= 0.1) return String.format(Locale.US, "%.4f", d);
else return String.format(Locale.US, "%s", d);
}
public static String toString(float f) {
float abs = Math.abs(f);
if (abs % 1.0f == 0) return String.format(Locale.US, "%.0f", f);
else if (abs >= 1000) return String.format(Locale.US, "%.0f", f);
else if (abs >= 0.1f) return String.format(Locale.US, "%.4f", f);
else return String.format(Locale.US, "%s", f);
}
public static String toString(Throwable t, Function<Throwable, String> stringify) {