]> git.basschouten.com Git - openhab-addons.git/blob
cf8ef3bb587e6eb6e010660c568d437db221149a
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.sensorcommunity.internal.utils;
14
15 import org.eclipse.jdt.annotation.NonNullByDefault;
16
17 /**
18  * The {@link NumberUtils} class provides helpers for converting Numbers.
19  *
20  * @author Bernd Weymann - Initial contribution
21  */
22 @NonNullByDefault
23 public class NumberUtils {
24     public static final double UNDEF = Double.NaN;
25
26     public static double round(Object o, int places) {
27         double value = convert(o);
28
29         // for negative places return plain number
30         if (places < 0) {
31             return value;
32         }
33
34         long factor = (long) Math.pow(10, places);
35         value = value * factor;
36         long tmp = Math.round(value);
37         return (double) tmp / factor;
38     }
39
40     public static double convert(Object o) {
41         // ensure value not null
42         double value = UNDEF;
43         if (o instanceof Number) {
44             value = ((Number) o).doubleValue();
45         } else if (o instanceof String) {
46             value = Double.parseDouble(o.toString());
47         }
48         return value;
49     }
50 }