1 package org.djunits.formatter;
2
3 /**
4 * Formatter of values with width and precision.
5 * <p>
6 * Copyright (c) 2025-2026 Delft University of Technology, Jaffalaan 5, 2628 BX Delft, the Netherlands. All rights reserved. See
7 * for project information <a href="https://djunits.org" target="_blank">https://djunits.org</a>. The DJUNITS project is
8 * distributed under a <a href="https://djunits.org/docs/license.html" target="_blank">three-clause BSD-style license</a>.
9 * @author Alexander Verbraeck
10 * @author Peter Knoppers
11 */
12 public final class Formatter
13 {
14 /**
15 * This class shall never be instantiated.
16 */
17 private Formatter()
18 {
19 // Prevent instantiation of this class
20 }
21
22 /** Default number of fraction digits. */
23 public static final int DEFAULTPRECISION = 3;
24
25 /**
26 * Build a format string.
27 * @param width the number of characters in the result
28 * @param precision the number of fractional digits in the result
29 * @param converter the format conversion specifier
30 * @return suitable for formatting a float or double
31 */
32 static String formatString(final int width, final int precision, final String converter)
33 {
34 return String.format("%%%d.%d%s", width, precision, converter);
35 }
36
37 /**
38 * Format a floating point value.
39 * @param value the value to format
40 * @param width the number of characters in the result
41 * @param precision the number of fractional digits in the result
42 * @return the formatted floating point value
43 */
44 public static String format(final double value, final int width, final int precision)
45 {
46 if (0 == value || Math.abs(value) > 0.01 && Math.abs(value) < 9999.0)
47 {
48 return String.format(formatString(width, precision, "f"), value);
49 }
50 return String.format(formatString(width, precision, "e"), value);
51 }
52
53 /**
54 * Format a floating point value.
55 * @param value the value to format
56 * @param width the number of characters in the result
57 * @return the formatted floating point value
58 */
59 public static String format(final double value, final int width)
60 {
61 return format(value, width, Formatter.DEFAULTPRECISION);
62 }
63
64 /**
65 * Format a floating point value.
66 * @param value the value to format
67 * @return the formatted floating point value
68 */
69 public static String format(final double value)
70 {
71 return format(value, Format.DEFAULTSIZE, Formatter.DEFAULTPRECISION);
72 }
73
74 }