Question

I read the below post but that isn't exact my question or answer to my question: Hexadecimal Floating-Point,roundIng

Given a floating point number, how do I round it off to the nearest whole hex number and then clam it between o and FF in javascript? For example, after converted to hex:

1e.fffffffffffe -> 1f
1e.111111111111 -> 1e
ff.fffffffffffe -> ff
-0.111111111111 -> 00

Edit I came up with some half baked function, anyone cares to improve it?

function roundDblDigitHex(x) {
    x = Math.round(x);
    if (x < 0) x = 0;
    if (x > 255) x = 255;
    x = x.toString(16);
    if (x.length === 1) x = '0'+x;
    return x;
}
Was it helpful?

Solution

I like your solution (in the end, I would also just use Math.round()). Here is my suggestion (a little bit shorter, but the same code):

function roundDblDigitHex(x) {
    x = Math.min(Math.max(Math.round(x), 0), 255);

    return ("0" + x.toString(16)).slice(-2);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top