0

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.

user3565923
  • 153
  • 2
  • 12

1 Answers1

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