描述:
写一个方法roundIt(n), 参数n为一个带小数点的数值。若小数点左边长度小于右边,返回ceil(n), 若左>右,返回floor(n),若左=右,返回round(n)。
例如:
roundIt(3.45) should return 4 -> ceil(3.45)
roundIt(34.5) should return 34 -> floor(34.5)
roundIt(34.56) should return 35 -> round(34.56)
CodeWar:
function roundIt (n) {
let [left, right] = n.toString().split('.').map(x => x.length),
dx = left - right,
fn = dx < 0 ? Math.ceil : dx > 0 ? Math.floor : Math.round
return fn(n)
}
roundIt = n => {
let s = String(n).split('.'), s0 = s[0].length, s1 = s[1].length;
return n = s0 < s1 ? Math.ceil(n) : (s0 > s1) ? Math.floor(n) : Math.round(n);
}
本文介绍了一个独特的数值处理方法roundIt(n),该方法依据输入数值的小数点左右两边的位数差异来决定采用向上取整、向下取整还是常规四舍五入的方式进行处理。通过JavaScript实现,提供了具体的实现代码。
568

被折叠的 条评论
为什么被折叠?



