]> git.basschouten.com Git - openhab-addons.git/blob
3c312164264e62ebe9cabcda1de4418524751e8b
[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.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         }
36         int decimal = Integer.parseInt(hexRepresentation, 16);
37         BigDecimal level = new BigDecimal(100 * decimal).divide(new BigDecimal(255), RoundingMode.FLOOR);
38         return level.intValue();
39     }
40
41     public static String getHexRepresentation(int percentage) {
42         BigDecimal decimal = new BigDecimal(255 * percentage).divide(new BigDecimal(100), RoundingMode.CEILING);
43         return Integer.toHexString(decimal.intValue()).toUpperCase();
44     }
45 }