Skip to content

Commit 2c8a3da

Browse files
authored
Merge pull request #9 from deefrawley/better_precision
add smarter way to do float precisions. Fix #8
2 parents f707eb0 + 2af71b3 commit 2c8a3da

File tree

3 files changed

+23
-2
lines changed

3 files changed

+23
-2
lines changed

plugin.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
"Name": "General Converter",
55
"Description": "General weights and measures converter",
66
"Author": "deefrawley",
7-
"Version": "1.1.1",
7+
"Version": "1.1.2",
88
"Language": "python",
99
"Website": "https://github.com/deefrawley/Flow.Launcher.Plugin.GenConvert",
1010
"IcoPath": "assets/favicon.ico",

plugin/ui.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,10 +88,14 @@ def query(self, param: str) -> List[dict]:
8888
_("Check documentation for accepted units"),
8989
)
9090
else:
91+
c = do_convert["converted"]
92+
p = plugin.utils.smart_precision(
93+
locale.localeconv()["decimal_point"], c, 3
94+
)
9195
self.sendNormalMess(
9296
(do_convert["category"]),
9397
(
94-
f"{locale.format_string('%.6g', float(args[0]), grouping=True)} {args[1]} = {locale.format_string('%f', do_convert['converted'], grouping=True)} {args[2]}"
98+
f"{locale.format_string('%.10g', float(args[0]), grouping=True)} {args[1]} = {locale.format_string(f'%.{p}f', c, grouping=True)} {args[2]}"
9599
),
96100
f"assets/{do_convert['category']}.ico",
97101
)

plugin/utils.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import re
12
import plugin.units as gc_units
23
from plugin.extensions import _
34

@@ -112,3 +113,19 @@ def gen_convert(amount: float, from_unit: str, to_unit: str):
112113
"Problem converting {} and {}".format(from_unit, to_unit)
113114
)
114115
return conversions
116+
117+
118+
def smart_precision(separator, amount, preferred=3):
119+
str_amt = str(amount)
120+
dec_places = str_amt[::-1].find(separator)
121+
# whole number
122+
if dec_places == -1:
123+
return 0
124+
frac_part = str_amt[-dec_places::]
125+
# fraction is just zeroes
126+
if int(frac_part) == 0:
127+
return 0
128+
fnz = re.search(r"[1-9]", frac_part).start()
129+
if fnz < preferred:
130+
return preferred
131+
return fnz + 1

0 commit comments

Comments
 (0)