pythonnumpystring-formatting

Format np.float64 without leading digits


I need to format np.float64 floating values without leading digits before the dot, for example -2.40366982307 as -.240366982307E+01, in python.
This is to allow me to write in RINEX 3.03 the values with 4X, 4D19.12 formats. I have tried f"{x:.12E}" but it always has a leading 1 for numbers greater than 1. I have also tried np.format_float_positional and np.format_float_scientific but those don't have restrictions on leading digits.


Solution

  • I would go for something custom designed from scratch. I agree, however, I did not think about all the marginal cases that can occur.

    # Format a floating-point number to RINEX format
    def format_rinex(value):
        if not np.isfinite(value):
            return f"{value}"
    
        sign = '-' if value < 0 else ' '
        abs_value = np.abs(value)
        exponent = 1 + np.int32(np.floor(np.log10(abs_value))).item() if value != 0 else 0
        mantissa = abs_value / (10 ** exponent)
        mantissa_str = f'{mantissa:.12f}'.replace("0.", ".")
        return f'{sign}{mantissa_str}E{exponent:+03d}'
    

    Formats your example number into -.240366982307E+01.