Skip to content

Commit

Permalink
Merge pull request #9 from deefrawley/better_precision
Browse files Browse the repository at this point in the history
add smarter way to do float precisions. Fix #8
  • Loading branch information
deefrawley authored Jan 4, 2022
2 parents f707eb0 + 2af71b3 commit 2c8a3da
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
2 changes: 1 addition & 1 deletion plugin.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"Name": "General Converter",
"Description": "General weights and measures converter",
"Author": "deefrawley",
"Version": "1.1.1",
"Version": "1.1.2",
"Language": "python",
"Website": "https://github.com/deefrawley/Flow.Launcher.Plugin.GenConvert",
"IcoPath": "assets/favicon.ico",
Expand Down
6 changes: 5 additions & 1 deletion plugin/ui.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,10 +88,14 @@ def query(self, param: str) -> List[dict]:
_("Check documentation for accepted units"),
)
else:
c = do_convert["converted"]
p = plugin.utils.smart_precision(
locale.localeconv()["decimal_point"], c, 3
)
self.sendNormalMess(
(do_convert["category"]),
(
f"{locale.format_string('%.6g', float(args[0]), grouping=True)} {args[1]} = {locale.format_string('%f', do_convert['converted'], grouping=True)} {args[2]}"
f"{locale.format_string('%.10g', float(args[0]), grouping=True)} {args[1]} = {locale.format_string(f'%.{p}f', c, grouping=True)} {args[2]}"
),
f"assets/{do_convert['category']}.ico",
)
Expand Down
17 changes: 17 additions & 0 deletions plugin/utils.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import re
import plugin.units as gc_units
from plugin.extensions import _

Expand Down Expand Up @@ -112,3 +113,19 @@ def gen_convert(amount: float, from_unit: str, to_unit: str):
"Problem converting {} and {}".format(from_unit, to_unit)
)
return conversions


def smart_precision(separator, amount, preferred=3):
str_amt = str(amount)
dec_places = str_amt[::-1].find(separator)
# whole number
if dec_places == -1:
return 0
frac_part = str_amt[-dec_places::]
# fraction is just zeroes
if int(frac_part) == 0:
return 0
fnz = re.search(r"[1-9]", frac_part).start()
if fnz < preferred:
return preferred
return fnz + 1

0 comments on commit 2c8a3da

Please sign in to comment.