简体   繁体   English

最小最大和四舍五入的JavaScript

[英]min max and rounding hex in javascript

I read the below post but that isn't exact my question or answer to my question: Hexadecimal Floating-Point,roundIng 我阅读了以下帖子,但不完全是我的问题,也不是我的问题的答案: 十六进制浮点,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? 给定一个浮点数,我如何将其四舍五入为最接近的整个十六进制数,然后在JavaScript中的o和FF之间将其蛤lam呢? 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() ). 我喜欢您的解决方案(最后,我也将只使用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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM