2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.luxom.internal.handler.util;
15 import java.math.BigDecimal;
16 import java.math.RoundingMode;
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19 import org.eclipse.jdt.annotation.Nullable;
22 * converts the hexadecimal string representation to an integer value between 0 - 100
24 * @author Kris Jespers - Initial contribution
27 public class PercentageConverter {
29 * @param hexRepresentation
30 * @return if hexRepresentation == null return -1, otherwise return percentage
32 public static int getPercentage(@Nullable String hexRepresentation) {
33 if (hexRepresentation == null) {
36 int decimal = Integer.parseInt(hexRepresentation, 16);
37 BigDecimal level = new BigDecimal(100 * decimal).divide(new BigDecimal(255), RoundingMode.FLOOR);
38 return level.intValue();
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();