parent
75264a07a8
commit
0053511c66
@ -0,0 +1,47 @@
|
||||
def format_amount(amount: int, decimals: int) -> str:
|
||||
if amount < 0:
|
||||
amount = -amount
|
||||
sign = "-"
|
||||
else:
|
||||
sign = ""
|
||||
d = pow(10, decimals)
|
||||
s = (
|
||||
("%s%d.%0*d" % (sign, amount // d, decimals, amount % d))
|
||||
.rstrip("0")
|
||||
.rstrip(".")
|
||||
)
|
||||
return s
|
||||
|
||||
|
||||
def format_ordinal(number: int) -> str:
|
||||
return str(number) + {1: "st", 2: "nd", 3: "rd"}.get(
|
||||
4 if 10 <= number % 100 < 20 else number % 10, "th"
|
||||
)
|
||||
|
||||
|
||||
def format_plural(string: str, count: int, plural: str):
|
||||
"""
|
||||
Adds plural form to a string based on `count`.
|
||||
!! Does not work with irregular words !!
|
||||
|
||||
Example:
|
||||
>>> format_plural("We need {count} more {plural}", 3, "share")
|
||||
'We need 3 more shares'
|
||||
>>> format_plural("We need {count} more {plural}", 1, "share")
|
||||
'We need 1 more share'
|
||||
>>> format_plural("{count} {plural}", 4, "candy")
|
||||
'4 candies'
|
||||
"""
|
||||
if not all(s in string for s in ("{count}", "{plural}")):
|
||||
# string needs to have {count} and {plural} inside
|
||||
raise ValueError
|
||||
|
||||
if count == 0 or count > 1:
|
||||
if plural[-1] == "y":
|
||||
plural = plural[:-1] + "ies"
|
||||
elif plural[-1] in "hsxz":
|
||||
plural = plural + "es"
|
||||
else:
|
||||
plural = plural + "s"
|
||||
|
||||
return string.format(count=count, plural=plural)
|
@ -0,0 +1,34 @@
|
||||
from common import *
|
||||
|
||||
from trezor import strings
|
||||
|
||||
|
||||
class TestStrings(unittest.TestCase):
|
||||
|
||||
def test_format_amount(self):
|
||||
VECTORS = [
|
||||
(123456, 3, "123.456"),
|
||||
(4242, 7, "0.0004242"),
|
||||
(-123456, 3, "-123.456"),
|
||||
(-4242, 7, "-0.0004242"),
|
||||
]
|
||||
for v in VECTORS:
|
||||
self.assertEqual(strings.format_amount(v[0], v[1]), v[2])
|
||||
|
||||
|
||||
def test_format_plural(self):
|
||||
VECTORS = [
|
||||
("We need {count} more {plural}", 3, "share", "We need 3 more shares"),
|
||||
("We need {count} more {plural}", 1, "share", "We need 1 more share"),
|
||||
("We need {count} more {plural}", 1, "candy", "We need 1 more candy"),
|
||||
("We need {count} more {plural}", 7, "candy", "We need 7 more candies"),
|
||||
]
|
||||
for v in VECTORS:
|
||||
self.assertEqual(strings.format_plural(v[0], v[1], v[2]), v[3])
|
||||
|
||||
with self.assertRaises(ValueError):
|
||||
strings.format_plural("Hello", 1, "share")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
Loading…
Reference in new issue