Skip to content

Commit

Permalink
Fix decimal value_as_string (#722) (#753)
Browse files Browse the repository at this point in the history
Fixes #710

Co-authored-by: Sergii Mikhtoniuk <mikhtoniuk@gmail.com>
  • Loading branch information
alamb and sergiimk authored Sep 9, 2021
1 parent b8352fd commit f68afcc
Showing 1 changed file with 31 additions and 4 deletions.
35 changes: 31 additions & 4 deletions arrow/src/array/array_binary.rs
Original file line number Diff line number Diff line change
Expand Up @@ -744,12 +744,22 @@ impl DecimalArray {

#[inline]
pub fn value_as_string(&self, row: usize) -> String {
let decimal_string = self.value(row).to_string();
let value = self.value(row);
let value_str = value.to_string();

if self.scale == 0 {
decimal_string
value_str
} else {
let splits = decimal_string.split_at(decimal_string.len() - self.scale);
format!("{}.{}", splits.0, splits.1)
let (sign, rest) = value_str.split_at(if value >= 0 { 0 } else { 1 });

if rest.len() > self.scale {
// Decimal separator is in the middle of the string
let (whole, decimal) = value_str.split_at(value_str.len() - self.scale);
format!("{}.{}", whole, decimal)
} else {
// String has to be padded
format!("{}0.{:0>width$}", sign, rest, width = self.scale)
}
}
}

Expand Down Expand Up @@ -1240,6 +1250,23 @@ mod tests {
assert_eq!(16, decimal_array.value_length());
}

#[test]
fn test_decimal_array_value_as_string() {
let mut decimal_builder = DecimalBuilder::new(7, 5, 3);
for value in [123450, -123450, 100, -100, 10, -10, 0] {
decimal_builder.append_value(value).unwrap();
}
let arr = decimal_builder.finish();

assert_eq!("123.450", arr.value_as_string(0));
assert_eq!("-123.450", arr.value_as_string(1));
assert_eq!("0.100", arr.value_as_string(2));
assert_eq!("-0.100", arr.value_as_string(3));
assert_eq!("0.010", arr.value_as_string(4));
assert_eq!("-0.010", arr.value_as_string(5));
assert_eq!("0.000", arr.value_as_string(6));
}

#[test]
fn test_decimal_array_fmt_debug() {
let values: Vec<i128> = vec![8887000000, -8887000000];
Expand Down

0 comments on commit f68afcc

Please sign in to comment.