You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Value.java 8.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.ss.formula.functions;
  16. import org.apache.poi.ss.formula.eval.ErrorEval;
  17. import org.apache.poi.ss.formula.eval.EvaluationException;
  18. import org.apache.poi.ss.formula.eval.NumberEval;
  19. import org.apache.poi.ss.formula.eval.OperandResolver;
  20. import org.apache.poi.ss.formula.eval.ValueEval;
  21. import org.apache.poi.ss.usermodel.DateUtil;
  22. import java.time.DateTimeException;
  23. /**
  24. * Implementation for Excel VALUE() function.<p>
  25. *
  26. * <b>Syntax</b>:<br> <b>VALUE</b>(<b>text</b>)<br>
  27. * <p>
  28. * Converts the text argument to a number. Leading and/or trailing whitespace is
  29. * ignored. Currency symbols and thousands separators are stripped out.
  30. * Scientific notation is also supported. If the supplied text does not convert
  31. * properly the result is <b>#VALUE!</b> error. Blank string converts to zero.
  32. */
  33. public final class Value extends Fixed1ArgFunction implements ArrayFunction {
  34. /**
  35. * "1,0000" is valid, "1,00" is not
  36. */
  37. private static final int MIN_DISTANCE_BETWEEN_THOUSANDS_SEPARATOR = 4;
  38. private static final Double ZERO = Double.valueOf(0.0);
  39. public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0) {
  40. ValueEval veText;
  41. try {
  42. veText = OperandResolver.getSingleValue(arg0, srcRowIndex, srcColumnIndex);
  43. } catch (EvaluationException e) {
  44. return e.getErrorEval();
  45. }
  46. String strText = OperandResolver.coerceValueToString(veText);
  47. Double result = convertTextToNumber(strText);
  48. if (result == null) result = parseDateTime(strText);
  49. if (result == null) {
  50. return ErrorEval.VALUE_INVALID;
  51. }
  52. return new NumberEval(result.doubleValue());
  53. }
  54. @Override
  55. public ValueEval evaluateArray(ValueEval[] args, int srcRowIndex, int srcColumnIndex) {
  56. if (args.length != 1) {
  57. return ErrorEval.VALUE_INVALID;
  58. }
  59. return evaluateOneArrayArg(args[0], srcRowIndex, srcColumnIndex, (valA) ->
  60. evaluate(srcRowIndex, srcColumnIndex, valA)
  61. );
  62. }
  63. /**
  64. * TODO see if the same functionality is needed in {@link OperandResolver#parseDouble(String)}
  65. *
  66. * @return <code>null</code> if there is any problem converting the text
  67. */
  68. public static Double convertTextToNumber(String strText) {
  69. boolean foundCurrency = false;
  70. boolean foundUnaryPlus = false;
  71. boolean foundUnaryMinus = false;
  72. boolean foundPercentage = false;
  73. int len = strText.length();
  74. int i;
  75. for (i = 0; i < len; i++) {
  76. char ch = strText.charAt(i);
  77. if (Character.isDigit(ch) || ch == '.') {
  78. break;
  79. }
  80. switch (ch) {
  81. case ' ':
  82. // intervening spaces between '$', '-', '+' are OK
  83. continue;
  84. case '$':
  85. if (foundCurrency) {
  86. // only one currency symbols is allowed
  87. return null;
  88. }
  89. foundCurrency = true;
  90. continue;
  91. case '+':
  92. if (foundUnaryMinus || foundUnaryPlus) {
  93. return null;
  94. }
  95. foundUnaryPlus = true;
  96. continue;
  97. case '-':
  98. if (foundUnaryMinus || foundUnaryPlus) {
  99. return null;
  100. }
  101. foundUnaryMinus = true;
  102. continue;
  103. default:
  104. // all other characters are illegal
  105. return null;
  106. }
  107. }
  108. if (i >= len) {
  109. // didn't find digits or '.'
  110. if (foundCurrency || foundUnaryMinus || foundUnaryPlus) {
  111. return null;
  112. }
  113. return ZERO;
  114. }
  115. // remove thousands separators
  116. boolean foundDecimalPoint = false;
  117. int lastThousandsSeparatorIndex = Short.MIN_VALUE;
  118. StringBuilder sb = new StringBuilder(len);
  119. for (; i < len; i++) {
  120. char ch = strText.charAt(i);
  121. if (Character.isDigit(ch)) {
  122. sb.append(ch);
  123. continue;
  124. }
  125. switch (ch) {
  126. case ' ':
  127. String remainingTextTrimmed = strText.substring(i).trim();
  128. // support for value[space]%
  129. if (remainingTextTrimmed.equals("%")) {
  130. foundPercentage = true;
  131. break;
  132. }
  133. if (remainingTextTrimmed.length() > 0) {
  134. // intervening spaces not allowed once the digits start
  135. return null;
  136. }
  137. break;
  138. case '.':
  139. if (foundDecimalPoint) {
  140. return null;
  141. }
  142. if (i - lastThousandsSeparatorIndex < MIN_DISTANCE_BETWEEN_THOUSANDS_SEPARATOR) {
  143. return null;
  144. }
  145. foundDecimalPoint = true;
  146. sb.append('.');
  147. continue;
  148. case ',':
  149. if (foundDecimalPoint) {
  150. // thousands separators not allowed after '.' or 'E'
  151. return null;
  152. }
  153. int distanceBetweenThousandsSeparators = i - lastThousandsSeparatorIndex;
  154. // as long as there are 3 or more digits between
  155. if (distanceBetweenThousandsSeparators < MIN_DISTANCE_BETWEEN_THOUSANDS_SEPARATOR) {
  156. return null;
  157. }
  158. lastThousandsSeparatorIndex = i;
  159. // don't append ','
  160. continue;
  161. case 'E':
  162. case 'e':
  163. if (i - lastThousandsSeparatorIndex < MIN_DISTANCE_BETWEEN_THOUSANDS_SEPARATOR) {
  164. return null;
  165. }
  166. // append rest of strText and skip to end of loop
  167. sb.append(strText.substring(i));
  168. i = len;
  169. break;
  170. case '%':
  171. foundPercentage = true;
  172. break;
  173. default:
  174. // all other characters are illegal
  175. return null;
  176. }
  177. }
  178. if (!foundDecimalPoint) {
  179. if (i - lastThousandsSeparatorIndex < MIN_DISTANCE_BETWEEN_THOUSANDS_SEPARATOR) {
  180. return null;
  181. }
  182. }
  183. double d;
  184. try {
  185. d = Double.parseDouble(sb.toString());
  186. } catch (NumberFormatException e) {
  187. // still a problem parsing the number - probably out of range
  188. return null;
  189. }
  190. double result = foundUnaryMinus ? -d : d;
  191. return foundPercentage ? result / 100. : result;
  192. }
  193. public static Double parseDateTime(String pText) {
  194. try {
  195. return DateUtil.parseDateTime(pText);
  196. } catch (DateTimeException e) {
  197. return null;
  198. }
  199. }
  200. }