001/*-
002 * #%L
003 * HAPI FHIR JPA Server
004 * %%
005 * Copyright (C) 2014 - 2024 Smile CDR, Inc.
006 * %%
007 * Licensed under the Apache License, Version 2.0 (the "License");
008 * you may not use this file except in compliance with the License.
009 * You may obtain a copy of the License at
010 *
011 *      http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing, software
014 * distributed under the License is distributed on an "AS IS" BASIS,
015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
016 * See the License for the specific language governing permissions and
017 * limitations under the License.
018 * #L%
019 */
020package ca.uhn.fhir.jpa.dao.predicate;
021
022import ca.uhn.fhir.rest.param.ParamPrefixEnum;
023
024import java.math.BigDecimal;
025
026public interface SearchFuzzUtil {
027        /**
028         * Figures out the tolerance for a search. For example, if the user is searching for <code>4.00</code>, this method
029         * returns <code>0.005</code> because we shold actually match values which are
030         * <code>4 (+/-) 0.005</code> according to the FHIR specs.
031         */
032        static BigDecimal calculateFuzzAmount(ParamPrefixEnum cmpValue, BigDecimal theValue) {
033                if (cmpValue == ParamPrefixEnum.APPROXIMATE) {
034                        return theValue.multiply(new BigDecimal(0.1));
035                } else {
036                        String plainString = theValue.toPlainString();
037                        int dotIdx = plainString.indexOf('.');
038                        if (dotIdx == -1) {
039                                return new BigDecimal(0.5);
040                        }
041
042                        int precision = plainString.length() - (dotIdx);
043                        double mul = Math.pow(10, -precision);
044                        double val = mul * 5.0d;
045                        return new BigDecimal(val);
046                }
047        }
048}