Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixed-width floating point number format

In Java, I have the following code:

System.out.printf("%05.5f", myFloat);

This works well for any numbers which are less than 10, but for any number 10 or greater, the decimal places are trimmed to 5, but that doesn't compensate for the fact that the number before the decimal point is longer. I'd like to do one of the following:

12.3456
1.23456

(ie, the same number of digits), or:

12.34567
 2.34567

(ie, pad with spaces so that the decimal points and last digits line up).

I'd be happy if I could get either to work (both would be even better!).

Any thoughts? Thanks!

like image 235
joshlf Avatar asked Jul 10 '13 18:07

joshlf


People also ask

What is the width of floating point numbers?

IEEE 754 standard: binary32. The IEEE 754 standard specifies a binary32 as having: Sign bit: 1 bit. Exponent width: 8 bits.

What is the width of floating point numbers in Java?

Float is a single-precision value that has a width of 32 bits in storage.

How do you format floating point numbers in Python?

In Python, there are various methods for formatting data types. The %f formatter is specifically used for formatting float values (numbers with decimals). We can use the %f formatter to specify the number of decimal numbers to be returned when a floating point number is rounded up.

What is float32_t?

For example float32_t denotes a single-precision floating-point type with approximately 7 decimal digits of precision (equivalent to binary32 in IEEE_floating_point). Floating-point types in C and C++ are specified to be allowed to have (optionally) implementation-specific widths and formats.


1 Answers

I figured out how to get it to do:

12.34567
 2.34567

Given a format string like "%x.yf", it will format with minimum width x, and post-decimal-point precision y. Since the pre-decimal point digits and the decimal point itself count towards the minimum width (x), the width has to be at least two larger than the precision. In particular, if a number is printed which is wider than the minimum width, it will not line up nicely with adjacent lines since those lines will be shorter. For example, if we try printing 10.1 and then 1.1 with a width of 3 and a precision of 1, we will get:

10.1
1.1

However, if we use a width of 4, 1.1 will be padded because it's not of the minimum width:

10.1
 1.1
like image 112
joshlf Avatar answered Oct 07 '22 00:10

joshlf