Search code examples
javafloating-pointstring-formattingformatting

Customizing Java Formatter to retain machine Precision


The default java String.format by default rounds floating point values to 6 digits, this can be overridden by using format specifiers in the format string.

How would one go about creating an instance of Formater that by default prints the full machine precision of the float or double to be formatted but retains the ability to specify a lower precision in the format string.

To exemplify, the following code

String.format("%f",1.23456789)

returns

1.234568

I want to create a custom Formatter so that

MyFormatter.format("%f",1.23456789)

returns

1.23456789

while producing identical output to String.format if the format string is "%.2f"

that is

String.format("%.2f",1.23456789).equals(MyFormatter.format("%.2f",1.23456789))

should evaluate to true


Solution

  • You may want to consider Java’s toString method. It produces just enough digits to uniquely distinguish the value from neighboring floating-point values. So simple numbers like 2 will produce short strings, but numbers that require more digits to be represented will produce longer strings.

    Because the number of digits depends on the type (finer types have closer neighbors), the results may be different for float and double operands, even when the value being converted is exactly the same. (Discussed here.)

    If possible, use built-in formatters, either directly or by manipulating their results in a string buffer. Converting between bases is a surprising complex problem and may involve extended precision arithmetic and mathematical proofs. Algorithms for doing correct conversion are known, and there are scientific papers describing them. So it is possible to write your own, but it is often better to rely on good work already done.

    In your case, you might use something like this:

    If format string is "%f", then use the toString method.
    Otherwise, use the format method.