繁体   English   中英

如何在Javascript中设置整数值

[英]How to floor integer value in Javascript

这听起来很奇怪,但我现在需要这个。实际上我有一个像这样的数组:

var arr = new Array(123, 432, 98, 227, 764);
var max = Math.max.apply(Math, arr); //calculate max = 764
var min = Math.min.apply(Math, arr); //calculate min = 123

现在我必须根据最小值和最大值制作几个范围:

 100 - 200 // as the min is 123 (range 100 ~ 200) 
 201 - 300
 301 - 400
 401 - 500
 501 - 600
 601 - 700
 701 - 800 // as the min is 764 (range 700 ~ 800)

制作范围只是一个循环问题。但计算最小和最大的范围我实现为:

function integerRound (digit) {
    var i = 0, msb; 
    while( digit > 0 ) {
      msb = digit % 10;
      digit = Math.floor( digit / 10 );
      i++;
    }
    while ( i > 1 ) {
      msb = msb + '0';
      i--;
    };
    return msb;
}

var lowerMin = integerRound(min); // 100
var lowerMax = integerRound(max); // 700

我的问题是 - 有没有什么好方法可以在javascript或jQuery中做到这一点?

鉴于此用例基本上是几个世纪的分类,是否有一些原因你不能简单地删除无关的部分:

century = value - (value % 100)

如果你真的需要从201开始的范围,依此类推,那么在做之前只需减去一个,然后再修正一个。

value -= 1;
century = value - (value % 100) + 1

这个怎么样:

var max = parseInt(Math.max.apply(Math, arr) / 100) * 100;
var min = parseInt(Math.min.apply(Math, arr) / 100) * 100

首先将数字除以100以获得小数点前的有效数字,使用parseInt截断(删除小数点后的所有内容,无效数字),然后再次乘以100以使值恢复到正确的大小。

暂无
暂无

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

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