简体   繁体   中英

Format int as int, but float as %.3f

I have a function that expects two cutoff values, called min_df and max_df . Either may be an int to denote an absolute frequency cutoff, or a float to denote a relative frequency. Now, I want to add some checks and give appropriate warning messages, but without too much clutter. This works:

if max_df < 0 or min_df < 0:
    raise ValueError, "neither max_df (%s) nor min_df (%s) may be <0" %
                      (max_df, min_df)

but with a float such as (1/3.) , the warning contains 0.333333333333 . I'd rather have it say 0.333 , so I tried %.3f , but that turns int values into floats as well and displays 2.000 for 2 .

How do I switch on type to get the right format? Do I need to build the format string before passing it to the % operator?

Update : I need something that works in Python 2.5, since that's the minimum version I'm targeting.

Keep it simple

def format_df(df):
    if isinstance(df, (int, long)):
        return "%d" % df
    elif isinstance(df, float):
        return "%.3f" % df
    else:
        return str(df) # fallback just in case

raise ValueError, "neither max_df (%s) nor min_df (%s) may be <0" %
                  (format_df(max_df), format_df(min_df))

How about this:

>>> "{:.4g}".format(1)
'1'
>>> "{:.4g}".format(1.3)
'1.3'
>>> "{:.4g}".format(1.333)
'1.333'
>>> "{:.4g}".format(1.333333)
'1.333'

However (since the 4 significant digits also include the integer part) you'd also get this:

>>> "{:.4g}".format(10.333)
'10.33'
>>> "{:.4g}".format(10000)
'1e+04'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM