Skip to content

Commit

Permalink
Fixed an issue with round (#207)
Browse files Browse the repository at this point in the history
* Fix the problem that the result has a decimal point when the round function, when the precision is 0.

* fix tests/test-functions.cpp:91 for round check
  • Loading branch information
zynfly authored Jul 1, 2021
1 parent c70fd58 commit 14f0d38
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 3 deletions.
6 changes: 5 additions & 1 deletion include/inja/renderer.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -439,7 +439,11 @@ class Renderer : public NodeVisitor {
const auto args = get_arguments<2>(node);
const int precision = args[1]->get<int>();
const double result = std::round(args[0]->get<double>() * std::pow(10.0, precision)) / std::pow(10.0, precision);
result_ptr = std::make_shared<json>(std::move(result));
if(0==precision){
result_ptr = std::make_shared<json>(int(result));
}else{
result_ptr = std::make_shared<json>(std::move(result));
}
json_tmp_stack.push_back(result_ptr);
json_eval_stack.push(result_ptr.get());
} break;
Expand Down
6 changes: 5 additions & 1 deletion single_include/inja/inja.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -3935,7 +3935,11 @@ class Renderer : public NodeVisitor {
const auto args = get_arguments<2>(node);
const int precision = args[1]->get<int>();
const double result = std::round(args[0]->get<double>() * std::pow(10.0, precision)) / std::pow(10.0, precision);
result_ptr = std::make_shared<json>(std::move(result));
if(0==precision){
result_ptr = std::make_shared<json>(int(result));
}else{
result_ptr = std::make_shared<json>(std::move(result));
}
json_tmp_stack.push_back(result_ptr);
json_eval_stack.push(result_ptr.get());
} break;
Expand Down
2 changes: 1 addition & 1 deletion test/test-functions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ TEST_CASE("functions") {
}

SUBCASE("round") {
CHECK(env.render("{{ round(4, 0) }}", data) == "4.0");
CHECK(env.render("{{ round(4, 0) }}", data) == "4");
CHECK(env.render("{{ round(temperature, 2) }}", data) == "25.68");
// CHECK_THROWS_WITH( env.render("{{ round(name, 2) }}", data), "[inja.exception.json_error]
// [json.exception.type_error.302] type must be number, but is string" );
Expand Down

0 comments on commit 14f0d38

Please sign in to comment.