如何使刻度四舍五入到最接近的 # 的倍数

How to make the scale to round to the nearest multiple of #?

本文关键字:最接近 何使刻 四舍五入      更新时间:2023-09-26
x.scale = d3.time.scale().domain(x.extent).range([0, dimensions.graph.width]);

此代码使用x.extent ( [Wed Aug 01 2012 00:00:00 GMT+0300 (EEST), Tue Aug 07 2012 00:00:00 GMT+0300 (EEST)] ( 和图形宽度 (1000( 来生成x值刻度。但是,我需要将此值四舍五入到最接近的 25 (Math.round(x/25)*25 的倍数(。

通过这样做,我想实现现在定义为的精确宽度刻度

x.axis = d3.svg.axis()
    .ticks(d3.time.days, 1)
    .tickSize(10, 5, 0)
    .scale(x.scale);

如何将x.scale扩展到四舍五入到最接近的 25 的倍数?

正确答案是 interpolateRound ,来自文档

返回两个数字 a 和 b 之间的插值器;插值器类似于 interpolateNumber,不同之处在于它将结果值舍入到最接近的整数。

var xScale = d3.scaleLinear()
    .domain([0, 100])
    .range([0, width])
    .interpolate(d3.interpolateRound); // <-- round interpolation

你在寻找不错的功能吗?

x.scale = d3.time.scale().domain(x.extent)
            .range([0, dimensions.graph.width]).nice();

也许我误解了,但是您不能在应用缩放函数后按照您的建议转换结果吗? 即:

function roundScale(origVal) { return Math.round(x.scale(origVal)/25) * 25;}

然后使用该值设置属性:

.attr("x", function(d) { return roundScale(d.value); }