0

Why is this JSTL block resulting 0.9999999999999999, and what is the fix?

<c:set var="one" value="0.1"/>
<c:set var="two" value="0.7"/>
<c:set var="three" value="0.1"/>
<c:set var="four" value="0.1"/>
<c:out  value="${one+two+three+four}"/>
Ganesh S
  • 510
  • 11
  • 19

1 Answers1

0

JB Nizet's comment is correct, but here's how to deal with it.

You should consider using the fmt:formatNumber function when dealing with floating point numbers. Here is a URL: http://www.tutorialspoint.com/jsp/jstl_format_formatnumber_tag.htm

And here is an example:

<c:set var="one" value="0.1"/>
<c:set var="two" value="0.7"/>
<c:set var="three" value="0.1"/>
<c:set var="four" value="0.1"/>
<fmt:formatNumber value="${one+two+three+four}" maxFractionDigits="2" />

Make sure to include this line at the top of your JSP code:

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
alfreema
  • 1,308
  • 14
  • 26