简体   繁体   English

十进制 - 删除尾随零并抑制科学记数法

[英]Decimal - remove trailing zeros and supress scientifict notation

I need a function which works like format_float_postional, but doesn't round.我需要一个像 format_float_postional 一样工作的函数,但不四舍五入。 It is function which:它的功能是:

  • should remove trailing zeros应该删除尾随零
  • doesn't round (problem with that)不圆(问题)
  • should supress scientifict notation应该禁止科学记数法
  • can be used with Decimal可以与小数一起使用

This is the closesest soultion I found: https://stackoverflow.com/a/58106536/3565923这是我发现的最接近的灵魂: https ://stackoverflow.com/a/58106536/3565923

import numpy as np
formated = np.format_float_positional((float(instance.factor)), trim="-")

Intance factor is a field in serializer.实例因子是序列化程序中的一个字段。 It is Decimal!是十进制!

class NewConversionSerializer(serializers.ModelSerializer):
    factor = serializers.DecimalField(max_digits=40, decimal_places=20)

At the moment I get: 0.55555555555555555550 -> 0.5555555555555556 I'd want it to be: 0.5555555555555555555目前我得到: 0.55555555555555555550 -> 0.5555555555555556我希望它是: 0.5555555555555555555

It would be great if both output and input would be decimal.如果输出和输入都是十进制的,那就太好了。

d1 = decimal.Decimal("0.555555555555555555555555550")
d2 = decimal.Decimal("0.555555555555555555555555550e-10")
"{:.1000f}".format(d1).rstrip('0')
"{:.1000f}".format(d2).rstrip('0')

Output:输出:

'0.55555555555555555555555555'
'0.000000000055555555555555555555555555'

It works (Python 3.8.10), but it needs a lot more testing in my opinion...它可以工作(Python 3.8.10),但在我看来它需要更多的测试......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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