decimal_to_binary
def decimal_to_binary(v: float, precison: int = 6) -> str: if v == 0: return '0b0' binary = '' integral = int(v) # integral part mantissa = v - integral # fractional part # conversion of integral part to binary equivalent # quotient, modulus = divmod(integral, 2) # while quotient: # binary += str(modulus) # quotient, modulus = divmod(quotient, 2) # binary += str(modulus) while integral: binary += str(integral % 2) integral //= 2 binary = binary[::-1] + '.' # conversion of fractional part to binary equaivalent while precison > 0: precison -= 1 mantissa *= 2 if mantissa == 1: binary += '1' rpartition = binary.rpartition('.') return '0b' + rpartition[0] + '.' + rpartition[2].ljust(precison, '0') elif mantissa > 1: binary += '1' mantissa -= 1 else: binary += '0' return '0b' + binary print(decimal_to_binary(13.7)) print(decimal_to_binary(8.1)) print(decimal_to_binary(.1)) print(decimal_to_binary(4.)) print(decimal_to_binary(4.5))
标签:binary,precison,Python,decimal,integral,utilities,mantissa,print From: https://www.cnblogs.com/dissipate/p/17275799.html