Skip to content

Commit c96a284

Browse files
committed
fix percentage formatting issues
1 parent a277525 commit c96a284

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

lib/algora/shared/util.ex

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -78,9 +78,8 @@ defmodule Algora.Util do
7878
def format_pct(percentage) do
7979
percentage
8080
|> Decimal.mult(100)
81-
|> Decimal.to_string()
82-
|> String.trim_trailing("0")
83-
|> String.trim_trailing(".")
81+
|> Decimal.normalize()
82+
|> Decimal.to_string(:normal)
8483
|> Kernel.<>("%")
8584
end
8685

test/algora/shared/util_test.exs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
defmodule Algora.UtilTest do
2+
use ExUnit.Case, async: true
3+
4+
alias Algora.Util
5+
6+
describe "format_pct/1" do
7+
test "formats decimal percentages correctly" do
8+
assert Util.format_pct(Decimal.new("1")) == "100%"
9+
assert Util.format_pct(Decimal.new("0.1")) == "10%"
10+
assert Util.format_pct(Decimal.new("0.156")) == "15.6%"
11+
assert Util.format_pct(Decimal.new("0.1567")) == "15.67%"
12+
assert Util.format_pct(Decimal.new("0.15678")) == "15.678%"
13+
assert Util.format_pct(Decimal.new("0")) == "0%"
14+
end
15+
16+
test "trims trailing zeros" do
17+
assert Util.format_pct(Decimal.new("0.1500")) == "15%"
18+
assert Util.format_pct(Decimal.new("0.1050")) == "10.5%"
19+
end
20+
end
21+
end

0 commit comments

Comments
 (0)