mpmath / mpmath

Python library for arbitrary-precision floating-point arithmetic
http://mpmath.org
BSD 3-Clause "New" or "Revised" License
963 stars 184 forks source link

Support for '%' presentation type in `mpf.__format__` #837

Closed javierelpianista closed 2 months ago

javierelpianista commented 3 months ago

I've been working on these presentation types, to complete the set. '%' is straightforward, just multiply the mpf by 100 and add a % sign at the end.

'n' is a lot trickier, since some locales may be difficult to program. For instance,

>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'en_IN.utf8')
>>> print('{:.10n}'.format(100000.25))
1,00,000.25

Would a partial implementation of 'n' (i.e., only care about thousands and decimal separators) be useful or should we not bother at all with it?

skirpichev commented 3 months ago

'n' is a lot trickier

Python as a language has much wider audience than mpmath and a lot of features, related to different locales, e.g.:

>>> float('٣.٣')
3.3

But

>>> mpmath.mpf('٣.٣')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/sk/src/mpmath/mpmath/ctx_mp_python.py", line 71, in __new__
    val = from_str(val, prec, rounding, base)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/sk/src/mpmath/mpmath/libmp/libmpf.py", line 1348, in from_str
    man, exp = str_to_man_exp(x, base)
               ^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/sk/src/mpmath/mpmath/libmp/libmpf.py", line 1312, in str_to_man_exp
    x = MPZ(x, base)
        ^^^^^^^^^^^^
ValueError: string contains non-ASCII characters
>>> gmpy2.mpfr('٣.٣')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: string contains non-ASCII characters

should we not bother at all with it?

I think we could skip this, unless someone will came with real use cases.

javierelpianista commented 3 months ago

I think we could skip this, unless someone will came with real use cases.

OK, so no 'n' presentation type.

I'll make a PR with '%' mode and then another one with the full documentation for __format__, if that's OK with you @skirpichev.

skirpichev commented 2 months ago

pr is ready for review: https://github.com/mpmath/mpmath/pull/847