十进制 - 删除尾随的零和替补科学符号

发布于 2025-02-11 10:55:43 字数 751 浏览 2 评论 0原文

我需要一个像format_float_postional一样起作用的函数,但没有圆形。它是函数:

  • 应删除尾随的零
  • 不是圆形的(问题),
  • Scientifict表示法,
  • 如果可以用十进制来使用

这是我发现的最近的灵魂: https://stackoverflow.com/a/58106536/3565923

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

intance因素是Serializer中的领域。这是小数!

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

目前我得到: 0.55555555555555555550-> 0.55555555555556 我希望它是:0.5555555555555555555

如果输出和输入是十进制的,那将是很棒的。

I need a function which works like format_float_postional, but doesn't round. 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

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

It would be great if both output and input would be decimal.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

好菇凉咱不稀罕他 2025-02-18 10:55:43
d1 = decimal.Decimal("0.555555555555555555555555550")
d2 = decimal.Decimal("0.555555555555555555555555550e-10")
"{:.1000f}".format(d1).rstrip('0')
"{:.1000f}".format(d2).rstrip('0')

输出:

'0.55555555555555555555555555'
'0.000000000055555555555555555555555555'

它有效(Python 3.8.10),但我认为它需要更多的测试...

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文