简体   繁体   中英

Format number to string according to template number

I would like to display a number according to the precision of another template/example number.

Like, having example_number = 0.0001 and being able to do format_fp_digits_like(example_number, another_number) ; with another_number=10.12345 I would get 10.1234 .

This is what I tried so far:

import math

def format_fp_digits_like(template_number, number):
    n_digits = len(str(int(number)))
    if '.' in str(template_number):
        n_fp_digits = len(str(math.modf(template_number)[0]).split(".")[-1])
    else:
        n_fp_digits = 0
    fs = "{:"+f"{n_digits}.{n_fp_digits}f"+"}"
    return fs.format(number)

assert format_fp_digits_like(0.0001, 16.12345) == "16.1234"
assert format_fp_digits_like(1, 16.123) == "16"
assert format_fp_digits_like(0.1, 8.5) == "8.5"

It works, but I find it clumsy. There is probably a better way?

You could also use string formatting:

def rounder(template_number, number):
    return ('{0:.%sf}' % len(str(template_number).split('.')[-1])).format(number)


rounder(0.0001, 10.12345)

'10.1235'

What about using round function.

def format_fp_digits_like(number_of_float, number):
    return str(round(number, number_of_float)) 

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