Skip to content

g format differs from Python #88

Open
@jariji

Description

@jariji

I think this might be a bug.

# Format.jl
julia> pyfmt(".3g", 12.34)
"12.340"

# Python 
In: format(12.34, ".3g")
Out: '12.3'

Activity

R3G3N3R4T0R

R3G3N3R4T0R commented on Mar 3, 2025

@R3G3N3R4T0R

Yes, the implementation is plain wrong. Currently in fmtcore.jl

Format.jl/src/fmtcore.jl

Lines 337 to 341 in 37c24b9

if 1.0e-4 <= ax < 1.0e6
_pfmt_f(out, fs, x)
else
_pfmt_e(out, fs, x)
end

fs is passed without regard on how to handle significant digits. The correct behavior is documented in Python's Format String documentation this repo referenced to.
I will see if I can do anything, currently this gives the correct behavior but I am not sure this is how they do it.

function _pfmt_g(out::IO, fs::FormatSpec, x::AbstractFloat)
    # number decomposition
    ax = abs(x)
    if 1.0e-4 <= ax < 1.0e6
        newprec = fs.prec - floor(Int, log10(x)) - 1
        _pfmt_f(out, FormatSpec(fs ;prec=newprec), x)
    else
        newprec = fs.prec - 1
        _pfmt_e(out, FormatSpec(fs ;prec=newprec), x)
    end
end
linked a pull request that will close this issue on Mar 3, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      `g` format differs from Python · Issue #88 · JuliaString/Format.jl