【问题标题】:min max and rounding hex in javascriptjavascript中的最小值最大值和舍入十六进制
【发布时间】:2014-04-08 20:02:27
【问题描述】:

我阅读了以下帖子,但这不是我的问题或对我的问题的回答:Hexadecimal Floating-Point,roundIng

给定一个浮点数,我如何将它四舍五入到最接近的整数十六进制数,然后在 javascript 中将它夹在 o 和 FF 之间?例如转换为十六进制后:

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

编辑 我想出了一些半生不熟的功能,有人愿意改进吗?

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;
}

【问题讨论】:

    标签: javascript hex rounding


    【解决方案1】:

    我喜欢你的解决方案(最后,我也会使用Math.round())。这是我的建议(有点短,但代码相同):

    function roundDblDigitHex(x) {
        x = Math.min(Math.max(Math.round(x), 0), 255);
    
        return ("0" + x.toString(16)).slice(-2);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-22
      • 2011-01-14
      相关资源
      最近更新 更多