Top Description Fields Constructors Methods
org.python.core.stringlib

public abstract Class FloatFormatter

extends AbstractFormatter
Class Inheritance
Known Direct Subclasses
org.python.core.PyFloat.Formatter
Imports
java.math.BigDecimal, .MathContext, .RoundingMode, org.python.core.stringlib.InternalFormat.FormatError, .InternalFormat.FormatOverflow, .InternalFormat.Spec

A class that provides the implementation of floating-point formatting. In a limited way, it acts like a StringBuilder to which text and one or more numbers may be appended, formatted according to the format specifier supplied at construction. These are ephemeral objects that are not, on their own, thread safe.

Field Summary

Modifier and TypeField and Description
private static final long
private int
lenExponent

The length of the exponent sign and digits or zero if there isn't one.

private int
lenFraction

The length of the fractional part, right of the decimal point.

private int
lenMarker

The length of the exponent marker ("e"), "inf" or "nan", or zero if there isn't one.

private int
lenPoint

If it contains no decimal point, this length is zero, and 1 otherwise.

pack-priv static final int
MAX_PRECISION

Limit the size of results.

private int
minFracDigits

If minFracDigits≥0, minimum digits to follow decimal point (where consulted).

pack-priv static final RoundingMode
ROUND_PY

The rounding mode dominant in the formatter.

private static final long
Inherited from org.python.core.stringlib.InternalFormat.AbstractFormatter:
byteslenSignlenWholemarkresultspecstart

Constructor Summary

AccessConstructor and Description
public
FloatFormatter(StringBuilder
destination buffer
result
,
InternalFormat.Spec
parsed conversion specification
spec
)

Construct the formatter from a client-supplied buffer, to which the result will be appended, and a specification.

public
FloatFormatter(InternalFormat.Spec
parsed conversion specification
spec
)

Construct the formatter from a specification, allocating a buffer internally for the result.

Method Summary

Modifier and TypeMethod and Description
public FloatFormatter
append(char
The character to append
c
)

Overrides org.python.core.stringlib.InternalFormat.AbstractFormatter.append.

Implements java.lang.Appendable.append.

Appends the specified character to this Appendable.
public FloatFormatter
append(CharSequence
The character sequence to append. If csq is null, then the four characters "null" are appended to this Appendable.
csq
)

Overrides org.python.core.stringlib.InternalFormat.AbstractFormatter.append.

Implements java.lang.Appendable.append.

Appends the specified character sequence to this Appendable.
public FloatFormatter
append(CharSequence
The character sequence from which a subsequence will be appended. If csq is null, then characters will be appended as if csq contained the four characters "null".
csq
,
int
The index of the first character in the subsequence
start
,
int
The index of the character following the last character in the subsequence
end
)

Overrides org.python.core.stringlib.InternalFormat.AbstractFormatter.append.

Implements java.lang.Appendable.append.

Appends a subsequence of the specified character sequence to this Appendable.
private void
appendExponent(int
exponent value to append
exp
)

Append the current value of exp in the format "e{:+02d}" (for example e+05, e-10, e+308 , etc.).

private void
appendExponential(CharSequence
from converting the value at a given precision.
digits
,
int
would be the exponent (in e-format), used to position the decimal point.
exp
)

Common code for g-format, none-format and r-format used when the exponent is such that an exponential presentation is chosen.

private void
appendFixed(CharSequence
from converting the value at a given precision.
digits
,
int
would be the exponent (in e-format), used to position the decimal point.
exp
,
int
of conversion (number of significant digits).
precision
)

Common code for g-format, none-format and r-format used when the exponent is such that a fixed-point presentation is chosen.

private void
appendPointAndTrailingZeros(int
smallest number of fractional digits on return
n
)

Append the trailing fractional zeros, as required by certain formats, so that the total number of fractional digits is no less than specified.

private void
appendTrailingZeros(int
smallest number of fractional digits on return
n
)

Append the trailing fractional zeros, as required by certain formats, so that the total number of fractional digits is no less than specified.

private void
ensurePointAndTrailingZeros(int
smallest number of fractional digits on return
n
)

Append a decimal point and trailing fractional zeros if necessary for 'e' and 'f' format.

public FloatFormatter

Returns:

this object
format
(double
to convert
value
)

Format a floating-point number according to the specification represented by this FloatFormatter.

public FloatFormatter

Returns:

this object
format
(double
to convert
value
,
String
to use before positive values (e.g. "+") or null to default to ""
positivePrefix
)

Format a floating-point number according to the specification represented by this FloatFormatter.

private void
format_e(double
to convert
value
,
String
to use before positive values (e.g. "+") or null to default to ""
positivePrefix
,
int
precision (maximum number of fractional digits)
precision
)

The e-format helper function of format(double, String) that uses Java's BigDecimal to provide conversion and rounding.

private void
format_f(double
to convert
value
,
String
to use before positive values (e.g. "+") or null to default to ""
positivePrefix
,
int
precision (maximum number of fractional digits)
precision
)

The f-format inner helper function of format(double, String) that uses Java's BigDecimal to provide conversion and rounding.

private void
format_g(double
to convert
value
,
String
to use before positive values (e.g. "+") or null to default to ""
positivePrefix
,
int
total number of significant digits (precision 0 behaves as 1)
precision
,
int
+precision = the exponent at which to resume using exponential notation
expThresholdAdj
)

Implementation of the variants of g-format, that uses Java's BigDecimal to provide conversion and rounding.

private void
format_r(double
to convert
value
,
String
to use before positive values (e.g. "+") or null to default to ""
positivePrefix
)

Implementation of r-format (float.__repr__) that uses Java's Double#toString(double) to provide conversion and rounding.

private int
indexOfMarker()

Return the index in result of the first letter.

private void
removeTrailingZeros(int
smallest number of fractional digits on return
n
)

Remove trailing zeros from the fractional part, as required by certain formats, leaving at least the number of fractional digits specified.

private static int

Returns:

the exponent
reprDigits
(double
to convert
value
,
int
maximum number of digits to return in buf.
maxDigits
,
StringBuilder
for digits of result (recommend size be 20)
buf
)

Convert a double to digits and an exponent for use in float.__repr__ (or r-format).

protected void
reset()

Overrides org.python.core.stringlib.InternalFormat.AbstractFormatter.reset.

Clear the instance variables describing the latest object in result, ready to receive a new one.
protected int[]
sectionLengths()

Overrides org.python.core.stringlib.InternalFormat.AbstractFormatter.sectionLengths.

Supports toString() by returning the lengths of the successive sections in the result buffer, used for navigation relative to start.
public void
setMinFracDigits(int
if <0 prevent truncation; if ≥0 the minimum number of fractional digits; when this is zero, and all fractional digits are zero, the decimal point will also be removed.
minFracDigits
)

Override the default truncation behaviour for the specification originally supplied.

private boolean

Returns:

true if the value was one of "0", "-0", "nan, "inf", or "-inf".
signAndSpecialNumber
(double
to convert
value
,
String
to use before positive values (e.g. "+") or null to default to ""
positivePrefix
)

Common code to deal with the sign, and the special cases "0", "-0", "nan, "inf", or "-inf".

public static int

Returns:

recommended a buffer size
size
(InternalFormat.Spec
parsed conversion specification
spec
)

Recommend a buffer size for a given specification, assuming one float is converted.

protected void
uppercase()

Overrides org.python.core.stringlib.InternalFormat.AbstractFormatter.uppercase.

Convert just the letters in the representation of the current number (in result) to upper case.
private void
zeroHelper(int
of conversion (number of significant digits).
precision
,
int
if zero, causes choice of exponential notation for zero.
expThreshold
)

Common code for g-format, none-format and r-format called when the conversion yields "inf", "nan" or zero.

Inherited from org.python.core.stringlib.InternalFormat.AbstractFormatter:
alignmentNotAllowedalternateFormNotAllowedalternateFormNotAllowedappendformatgetResultgroupDigitsisBytesmakeSpaceAtnotAllowednotAllowednotAllowedpadpadprecisionNotAllowedprecisionTooLargesetBytessetStartsignNotAllowedtoStringunknownFormatzeroPadAfterSignWithGroupingFixupzeroPaddingNotAllowed

Field Detail

EXP_MASKback to summary
private static final long EXP_MASK
lenExponentback to summary
private int lenExponent

The length of the exponent sign and digits or zero if there isn't one.

lenFractionback to summary
private int lenFraction

The length of the fractional part, right of the decimal point.

lenMarkerback to summary
private int lenMarker

The length of the exponent marker ("e"), "inf" or "nan", or zero if there isn't one.

lenPointback to summary
private int lenPoint

If it contains no decimal point, this length is zero, and 1 otherwise.

MAX_PRECISIONback to summary
pack-priv static final int MAX_PRECISION

Limit the size of results. No-one needs more than log(Double.MAX_VALUE) - log2(Double.MIN_VALUE) = 1383 digits.

minFracDigitsback to summary
private int minFracDigits

If minFracDigits≥0, minimum digits to follow decimal point (where consulted). When minFracDigits<0 this signifies "no truncation" mode, in which trailing zeros generated in the conversion are not removed.

ROUND_PYback to summary
pack-priv static final RoundingMode ROUND_PY

The rounding mode dominant in the formatter.

SIGN_MASKback to summary
private static final long SIGN_MASK

Constructor Detail

FloatFormatterback to summary
public FloatFormatter(StringBuilder result, InternalFormat.Spec spec)

Construct the formatter from a client-supplied buffer, to which the result will be appended, and a specification. Sets mark to the end of the buffer.

Parameters
result:StringBuilder

destination buffer

spec:InternalFormat.Spec

parsed conversion specification

FloatFormatterback to summary
public FloatFormatter(InternalFormat.Spec spec)

Construct the formatter from a specification, allocating a buffer internally for the result.

Parameters
spec:InternalFormat.Spec

parsed conversion specification

Method Detail

appendback to summary
public FloatFormatter append(char c)

Overrides org.python.core.stringlib.InternalFormat.AbstractFormatter.append.

Implements java.lang.Appendable.append.

Doc from java.lang.Appendable.append.

Appends the specified character to this Appendable.

Parameters
c:char

The character to append

Returns:FloatFormatter

A reference to this Appendable

Annotations
@Override
appendback to summary
public FloatFormatter append(CharSequence csq)

Overrides org.python.core.stringlib.InternalFormat.AbstractFormatter.append.

Implements java.lang.Appendable.append.

Doc from java.lang.Appendable.append.

Appends the specified character sequence to this Appendable.

Depending on which class implements the character sequence csq, the entire sequence may not be appended. For instance, if csq is a java.nio.CharBuffer then the subsequence to append is defined by the buffer's position and limit.

Parameters
csq:CharSequence

The character sequence to append. If csq is null, then the four characters "null" are appended to this Appendable.

Returns:FloatFormatter

A reference to this Appendable

Annotations
@Override
appendback to summary
public FloatFormatter append(CharSequence csq, int start, int end) throws IndexOutOfBoundsException

Overrides org.python.core.stringlib.InternalFormat.AbstractFormatter.append.

Implements java.lang.Appendable.append.

Doc from java.lang.Appendable.append.

Appends a subsequence of the specified character sequence to this Appendable.

An invocation of this method of the form out.append(csq, start, end) when csq is not null, behaves in exactly the same way as the invocation

    out.append(csq.subSequence(start, end)) 
Parameters
csq:CharSequence

The character sequence from which a subsequence will be appended. If csq is null, then characters will be appended as if csq contained the four characters "null".

start:int

The index of the first character in the subsequence

end:int

The index of the character following the last character in the subsequence

Returns:FloatFormatter

A reference to this Appendable

Annotations
@Override
Exceptions
IndexOutOfBoundsException:
If start or end are negative, start is greater than end, or end is greater than csq.length()
appendExponentback to summary
private void appendExponent(int exp)

Append the current value of exp in the format "e{:+02d}" (for example e+05, e-10, e+308 , etc.).

Parameters
exp:int

exponent value to append

appendExponentialback to summary
private void appendExponential(CharSequence digits, int exp)

Common code for g-format, none-format and r-format used when the exponent is such that an exponential presentation is chosen. Normally the method removes trailing digits so as to shorten the presentation without loss of significance. Although no minimum number of fractional digits is enforced in the exponential presentation, when minFracDigits<0 this signifies "no truncation" mode, in which trailing zeros generated in the conversion are not removed. This supports "%#g" format.

Parameters
digits:CharSequence

from converting the value at a given precision.

exp:int

would be the exponent (in e-format), used to position the decimal point.

appendFixedback to summary
private void appendFixed(CharSequence digits, int exp, int precision)

Common code for g-format, none-format and r-format used when the exponent is such that a fixed-point presentation is chosen. Normally the method removes trailing digits so as to shorten the presentation without loss of significance. This method respects the minimum number of fractional digits (digits after the decimal point), in member minFracDigits, which is 0 for g-format and 1 for none-format and r-format. When minFracDigits<0 this signifies "no truncation" mode, in which trailing zeros generated in the conversion are not removed. This supports "%#g" format.

Parameters
digits:CharSequence

from converting the value at a given precision.

exp:int

would be the exponent (in e-format), used to position the decimal point.

precision:int

of conversion (number of significant digits).

appendPointAndTrailingZerosback to summary
private void appendPointAndTrailingZeros(int n)

Append the trailing fractional zeros, as required by certain formats, so that the total number of fractional digits is no less than specified. If there is no decimal point originally (and therefore no fractional part), the method will add a decimal point, even if it adds no zeros.

Parameters
n:int

smallest number of fractional digits on return

appendTrailingZerosback to summary
private void appendTrailingZeros(int n)

Append the trailing fractional zeros, as required by certain formats, so that the total number of fractional digits is no less than specified. If n<=0, the method leaves the result buffer unchanged.

Parameters
n:int

smallest number of fractional digits on return

ensurePointAndTrailingZerosback to summary
private void ensurePointAndTrailingZeros(int n)

Append a decimal point and trailing fractional zeros if necessary for 'e' and 'f' format. This should not be called if the result is not numeric ("inf" for example). This method deals with the following complexities: on return there will be at least the number of fractional digits specified in the argument n, and at least minFracDigits; further, if minFracDigits<0, signifying the "alternate mode" of certain formats, the method will ensure there is a decimal point, even if there are no fractional digits to follow.

Parameters
n:int

smallest number of fractional digits on return

formatback to summary
public FloatFormatter format(double value) throws FormatOverflow, FormatError

Format a floating-point number according to the specification represented by this FloatFormatter.

Parameters
value:double

to convert

Returns:FloatFormatter

this object

Exceptions
FormatOverflow:
if the precision is too large
FormatError:
if an unsupported format character is encountered
formatback to summary
public FloatFormatter format(double value, String positivePrefix) throws FormatOverflow, FormatError

Format a floating-point number according to the specification represented by this FloatFormatter. The conversion type, precision, and flags for grouping or percentage are dealt with here. At the point this is used, we know the spec is one of the floating-point types. This entry point allows explicit control of the prefix of positive numbers, overriding defaults for the format type.

Parameters
value:double

to convert

positivePrefix:String

to use before positive values (e.g. "+") or null to default to ""

Returns:FloatFormatter

this object

Exceptions
FormatOverflow:
if the precision is too large
FormatError:
if an unsupported format character is encountered
format_eback to summary
private void format_e(double value, String positivePrefix, int precision)

The e-format helper function of format(double, String) that uses Java's BigDecimal to provide conversion and rounding. The converted number is appended to the result buffer, and start will be set to the index of its first character.

Parameters
value:double

to convert

positivePrefix:String

to use before positive values (e.g. "+") or null to default to ""

precision:int

precision (maximum number of fractional digits)

format_fback to summary
private void format_f(double value, String positivePrefix, int precision)

The f-format inner helper function of format(double, String) that uses Java's BigDecimal to provide conversion and rounding. The converted number is appended to the result buffer, and start will be set to the index of its first character.

Parameters
value:double

to convert

positivePrefix:String

to use before positive values (e.g. "+") or null to default to ""

precision:int

precision (maximum number of fractional digits)

format_gback to summary
private void format_g(double value, String positivePrefix, int precision, int expThresholdAdj)

Implementation of the variants of g-format, that uses Java's BigDecimal to provide conversion and rounding. These variants are g-format proper, alternate g-format (available for "%#g" formatting), n-format (as g but subsequently "internationalised"), and none-format (type code Spec.NONE).

None-format is the basis of float.__str__.

According to the Python documentation for g-format, the precise rules are as follows: suppose that the result formatted with presentation type 'e' and precision p-1 would have exponent exp. Then if -4 <= exp < p, the number is formatted with presentation type 'f' and precision p-1-exp. Otherwise, the number is formatted with presentation type 'e' and precision p-1. In both cases insignificant trailing zeros are removed from the significand, and the decimal point is also removed if there are no remaining digits following it.

The Python documentation says none-format is the same as g-format, but the observed behaviour differs from this, in that f-format is only used if -4 <= exp < p-1 (i.e. one less), and at least one digit to the right of the decimal point is preserved in the f-format (but not the e-format). That behaviour is controlled through the following arguments, with these recommended values:

Recommended values for formatting arguments
type precision minFracDigits expThresholdAdj expThreshold
g p 0 0 p
#g p - 0 p
\0 p 1 -1 p-1
__str__ 12 1 -1 11
Parameters
value:double

to convert

positivePrefix:String

to use before positive values (e.g. "+") or null to default to ""

precision:int

total number of significant digits (precision 0 behaves as 1)

expThresholdAdj:int

+precision = the exponent at which to resume using exponential notation

format_rback to summary
private void format_r(double value, String positivePrefix)

Implementation of r-format (float.__repr__) that uses Java's Double#toString(double) to provide conversion and rounding. That method gives us almost what we need, but not quite (sometimes it yields 18 digits): here we always round to 17 significant digits. Much of the formatting after conversion is shared with format_g(double, String, int, int, int). minFracDigits is consulted since while float.__repr__ truncates to one digit, within complex.__repr__ we truncate fully.

Parameters
value:double

to convert

positivePrefix:String

to use before positive values (e.g. "+") or null to default to ""

indexOfMarkerback to summary
private int indexOfMarker()

Return the index in result of the first letter. This is a helper for uppercase() and getExponent()

removeTrailingZerosback to summary
private void removeTrailingZeros(int n)

Remove trailing zeros from the fractional part, as required by certain formats, leaving at least the number of fractional digits specified. If the resultant number of fractional digits is zero, this method will also remove the trailing decimal point (if there is one).

Parameters
n:int

smallest number of fractional digits on return

reprDigitsback to summary
private static int reprDigits(double value, int maxDigits, StringBuilder buf)

Convert a double to digits and an exponent for use in float.__repr__ (or r-format). This method takes advantage of (or assumes) a close correspondence between Double#toString(double) and Python float.__repr__. The correspondence appears to be exact, insofar as the Java method produces the minimal non-zero digit string. It mostly chooses the same number of digits (and the same digits) as the CPython repr, but in a few cases Double.toString produces more digits. This method truncates to the number maxDigits, which in practice is always 17.

Parameters
value:double

to convert

maxDigits:int

maximum number of digits to return in buf.

buf:StringBuilder

for digits of result (recommend size be 20)

Returns:int

the exponent

resetback to summary
protected void reset()

Overrides org.python.core.stringlib.InternalFormat.AbstractFormatter.reset.

Doc from org.python.core.stringlib.InternalFormat.AbstractFormatter.reset.

Clear the instance variables describing the latest object in result, ready to receive a new one. This is called from setStart(). Subclasses override this method and call setStart() at the start of their format method.

Annotations
@Override
sectionLengthsback to summary
protected int[] sectionLengths()

Overrides org.python.core.stringlib.InternalFormat.AbstractFormatter.sectionLengths.

Doc from org.python.core.stringlib.InternalFormat.AbstractFormatter.sectionLengths.

Supports toString() by returning the lengths of the successive sections in the result buffer, used for navigation relative to start. The toString method shows a '|' character between each section when it prints out the buffer. Override this when you define more lengths in the subclass.

Returns:int[]

the lengths of the successive sections

Annotations
@Override
setMinFracDigitsback to summary
public void setMinFracDigits(int minFracDigits)

Override the default truncation behaviour for the specification originally supplied. Some formats remove trailing zero digits, trimming to zero or one. Set member minFracDigits, to modify this behaviour.

Parameters
minFracDigits:int

if <0 prevent truncation; if ≥0 the minimum number of fractional digits; when this is zero, and all fractional digits are zero, the decimal point will also be removed.

signAndSpecialNumberback to summary
private boolean signAndSpecialNumber(double value, String positivePrefix)

Common code to deal with the sign, and the special cases "0", "-0", "nan, "inf", or "-inf". If the method returns false, we have started a non-zero number and the sign is already in result. The client need then only encode abs(value). If the method returns true, and lenMarker==0, the value was "0" or "-0": the caller may have to zero-extend this, and/or add an exponent, to match the requested format. If the method returns true, and lenMarker>0, the method has placed "nan, "inf" in the result buffer (preceded by a sign if necessary).

Parameters
value:double

to convert

positivePrefix:String

to use before positive values (e.g. "+") or null to default to ""

Returns:boolean

true if the value was one of "0", "-0", "nan, "inf", or "-inf".

sizeback to summary
public static int size(InternalFormat.Spec spec)

Recommend a buffer size for a given specification, assuming one float is converted. This will be a "right" answer for e and g-format, and for f-format with values up to 9,999,999.

Parameters
spec:InternalFormat.Spec

parsed conversion specification

Returns:int

recommended a buffer size

uppercaseback to summary
protected void uppercase()

Overrides org.python.core.stringlib.InternalFormat.AbstractFormatter.uppercase.

Convert just the letters in the representation of the current number (in result) to upper case. (That's the exponent marker or the "inf" or "nan".)

Annotations
@Override
zeroHelperback to summary
private void zeroHelper(int precision, int expThreshold)

Common code for g-format, none-format and r-format called when the conversion yields "inf", "nan" or zero. The method completes formatting of the zero, with the appropriate number of decimal places or (in particular circumstances) exponential; notation.

Parameters
precision:int

of conversion (number of significant digits).

expThreshold:int

if zero, causes choice of exponential notation for zero.