1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef ANDROID_BASE_PARSEDOUBLE_H
18 #define ANDROID_BASE_PARSEDOUBLE_H
19 
20 #include <errno.h>
21 #include <stdlib.h>
22 
23 #include <limits>
24 
25 namespace android {
26 namespace base {
27 
28 // Parse double value in the string 's' and sets 'out' to that value.
29 // Optionally allows the caller to define a 'min' and 'max' beyond which
30 // otherwise valid values will be rejected. Returns boolean success.
31 static inline bool ParseDouble(const char* s, double* out,
32                                double min = std::numeric_limits<double>::lowest(),
33                                double max = std::numeric_limits<double>::max()) {
34   errno = 0;
35   char* end;
36   double result = strtod(s, &end);
37   if (errno != 0 || s == end || *end != '\0') {
38     return false;
39   }
40   if (result < min || max < result) {
41     return false;
42   }
43   *out = result;
44   return true;
45 }
46 
47 }  // namespace base
48 }  // namespace android
49 
50 #endif  // ANDROID_BASE_PARSEDOUBLE_H
51