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

Fred Foo picture Fred Foo · Sep 19, 2011 · Viewed 17.3k times · Source

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.

Answer

grep picture grep · Sep 19, 2011

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))