Merge pull request #174 from totalgee/develop

Support scientific notation for floating point (issue #173)
This commit is contained in:
Jason Turner 2015-04-29 16:50:39 -06:00
commit c52ad3d827
2 changed files with 51 additions and 8 deletions

View File

@ -16,6 +16,7 @@
#include <sstream>
#include <string>
#include <vector>
#include <cctype>
#include "../dispatchkit/boxed_value.hpp"
#include "chaiscript_common.hpp"
@ -423,6 +424,37 @@ namespace chaiscript
return retval;
}
/// Reads the optional exponent (scientific notation) and suffix for a Float
bool read_exponent_and_suffix() {
// Support a form of scientific notation: 1e-5, 35.5E+8, 0.01e19
if (has_more_input() && (std::tolower(*m_input_pos) == 'e')) {
++m_input_pos;
++m_col;
if (has_more_input() && ((*m_input_pos == '-') || (*m_input_pos == '+'))) {
++m_input_pos;
++m_col;
}
auto exponent_pos = m_input_pos;
while (has_more_input() && char_in_alphabet(*m_input_pos,detail::int_alphabet) ) {
++m_input_pos;
++m_col;
}
if (m_input_pos == exponent_pos) {
// Require at least one digit after the exponent
return false;
}
}
// Parse optional float suffix
while (has_more_input() && char_in_alphabet(*m_input_pos, detail::float_suffix_alphabet))
{
++m_input_pos;
++m_col;
}
return true;
}
/// Reads a floating point value from input, without skipping initial whitespace
bool Float_() {
@ -432,7 +464,11 @@ namespace chaiscript
++m_col;
}
if (has_more_input() && (*m_input_pos == '.')) {
if (has_more_input() && (std::tolower(*m_input_pos) == 'e')) {
// The exponent is valid even without any decimal in the Float (1e8, 3e-15)
return read_exponent_and_suffix();
}
else if (has_more_input() && (*m_input_pos == '.')) {
++m_input_pos;
++m_col;
if (has_more_input() && char_in_alphabet(*m_input_pos,detail::int_alphabet)) {
@ -441,13 +477,8 @@ namespace chaiscript
++m_col;
}
while (has_more_input() && char_in_alphabet(*m_input_pos, detail::float_suffix_alphabet))
{
++m_input_pos;
++m_col;
}
return true;
// After any decimal digits, support an optional exponent (3.7e3)
return read_exponent_and_suffix();
} else {
--m_input_pos;
--m_col;

View File

@ -5,3 +5,15 @@ assert_equal(1.2, 1.2)
assert_equal(true, .5 > 0)
assert_equal(true, .5 < 1)
assert_equal(0.5, .5)
// Scientific notation tests
assert_equal(to_string(-1.7e30f), "-1.7e+30")
assert_equal(to_string(+17.9E04), "179000")
assert_equal(to_string(-1.7e+300), "-1.7e+300")
assert_equal(to_string(-1.7e-300), "-1.7e-300")
assert_equal(to_string(17.5e30l), "1.75e+31")
assert_equal(to_string(1/3.14159e300L), "3.1831e-301")
assert_equal(to_string(1.0 / 12345), "8.10045e-05")
assert_equal(to_string(3e8F), "3e+08")
assert_equal(to_string(-15E-8*3e8), "-45")
assert_equal(to_string(-0.5e+3+20e-01), "-498")