]> git.basschouten.com Git - openhab-addons.git/blob
f6fe677d8ebc8ee453caf473b6b4eff0fd8ed11f
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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.luxom.internal.handler.util;
14
15 import java.math.BigDecimal;
16 import java.math.RoundingMode;
17
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19 import org.eclipse.jdt.annotation.Nullable;
20
21 /**
22  * converts the hexadecimal string representation to an integer value between 0 - 100
23  *
24  * @author Kris Jespers - Initial contribution
25  */
26 @NonNullByDefault
27 public class PercentageConverter {
28     /**
29      * @param hexRepresentation
30      * @return if hexRepresentation == null return -1, otherwise return percentage
31      */
32     public static int getPercentage(@Nullable String hexRepresentation) {
33         if (hexRepresentation == null)
34             return -1;
35         int decimal = Integer.parseInt(hexRepresentation, 16);
36         BigDecimal level = new BigDecimal(100 * decimal).divide(new BigDecimal(255), RoundingMode.FLOOR);
37         return level.intValue();
38     }
39
40     public static String getHexRepresentation(int percentage) {
41         BigDecimal decimal = new BigDecimal(255 * percentage).divide(new BigDecimal(100), RoundingMode.CEILING);
42         return Integer.toHexString(decimal.intValue()).toUpperCase();
43     }
44 }