Skip to content

Commit 312f8c8

Browse files
committed
Preserve float bar labels for integer-valued floats
1 parent 7972fb9 commit 312f8c8

2 files changed

Lines changed: 26 additions & 4 deletions

File tree

spec/unicode_plot_spec.cr

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -265,8 +265,17 @@ describe UnicodePlot do
265265
p = UnicodePlot.barplot(["int", "float", "mixed"], [3, 3.0, 12])
266266
s = p.to_s
267267

268-
s.should contain(" 3 ")
269-
s.should_not contain("3.0")
268+
s.should contain(" 3.0 ")
269+
s.should contain(" 12.0 ")
270+
end
271+
272+
it "preserves explicit float labels for integer-valued floats" do
273+
p = UnicodePlot.barplot(["a", "b", "c"], [3.0, 7.0, 12.0])
274+
s = p.to_s
275+
276+
s.should contain(" 3.0 ")
277+
s.should contain(" 7.0 ")
278+
s.should contain(" 12.0 ")
270279
end
271280

272281
it "accepts integer arrays when appending bar values" do

src/unicode_plot/interface/barplot.cr

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ module UnicodePlot
1919
compact_labels : Bool = false,
2020
compact : Bool = false,
2121
title : String = "",
22+
integer_labels : Bool = false,
2223
) : Plot
2324
raise ArgumentError.new("text and heights must have the same length") unless text.size == heights.size
2425
raise ArgumentError.new("all values must be >= 0") unless heights.all? { |val| val >= 0 }
@@ -40,7 +41,11 @@ module UnicodePlot
4041
end
4142

4243
char_width = width || default_width
43-
fmt = ->(x : Float64) { nice_repr(x, unicode_exponent, thousands_separator) }
44+
fmt = if integer_labels
45+
->(x : Float64) { nice_repr(x.round.to_i64, unicode_exponent, thousands_separator) }
46+
else
47+
->(x : Float64) { bar_float_label(x, unicode_exponent, thousands_separator) }
48+
end
4449
area = BarplotGraphics.new(
4550
final_heights, char_width,
4651
symbols: symbols, color: color, maximum: maximum,
@@ -120,7 +125,15 @@ module UnicodePlot
120125
end
121126

122127
private def barplot_integer(text : Array(String), heights : Array(T), **kwargs) : Plot forall T
123-
barplot(text, heights.map(&.to_f), **kwargs)
128+
barplot(text, heights.map(&.to_f), **kwargs, integer_labels: true)
129+
end
130+
131+
private def bar_float_label(value : Float64, unicode_exponent : Bool, thousands_separator : Char) : String
132+
if value.finite? && value == value.round
133+
"#{nice_repr(value.round.to_i64, unicode_exponent, thousands_separator)}.0"
134+
else
135+
nice_repr(value, unicode_exponent, thousands_separator)
136+
end
124137
end
125138

126139
# Get a representative color from a BarplotGraphics for legend labeling

0 commit comments

Comments
 (0)