Skip to content

Commit

Permalink
Parsing negative numbers now returns negative values
Browse files Browse the repository at this point in the history
  • Loading branch information
jimhester committed Jun 8, 2016
1 parent 6e09e41 commit 37a897d
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 2 deletions.
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
than numeric vectors (#357, @jimhester).
* Add `na` arguments to `parse_date()` `parse_time()` and `parse_datetime()`
(#413, @jimhester).
* Fix bug when parsing negative number returns a positive value (#308,
@jimhester).

* Fix bug when detecting column types for single row files without headers
(#333, @jimhester).
Expand Down
6 changes: 4 additions & 2 deletions src/QiParsers.h
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,15 @@ inline bool parseNumber(char decimalMark, char groupingMark, Iterator& first,
double sum = 0, denom = 1;
NumberState state = STATE_INIT;
bool seenNumber = false;
double sign = 1.0;

Iterator cur = first;
for(; cur != last; ++cur) {
switch(state) {
case STATE_INIT:
if (*cur == '-') {
state = STATE_LHS;
sign = -1.0;
} else if (*cur == decimalMark) {
state = STATE_RHS;
} else if (*cur >= '0' && *cur <= '9') {
Expand Down Expand Up @@ -100,14 +102,14 @@ inline bool parseNumber(char decimalMark, char groupingMark, Iterator& first,
break;
case STATE_FIN:
last = cur++;
res = sum;
res = sign * sum;
return seenNumber;
}
}

// Hit the end of the string, so must be done
last = cur;
res = sum;
res = sign * sum;

// Only true if we saw a number and reached the end of the string without
// finishing the number
Expand Down
8 changes: 8 additions & 0 deletions tests/testthat/test-parsing-numeric.R
Original file line number Diff line number Diff line change
Expand Up @@ -75,3 +75,11 @@ test_that("read_tsv passes on decimal_mark", {
out <- read_tsv("x\n1,5", locale = es_MX)
expect_equal(out$x, 1.5)
})

# Negative numbers -----------------------------------------------------------

test_that("negative numbers return negative values", {
expect_equal(parse_number("-2"), -2)

expect_equal(parse_number("-100,000.00"), -100000)
})

0 comments on commit 37a897d

Please sign in to comment.