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;
}
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.