JSアプリケーション--float型数値を操作し、2日間の間隔日数を取得する
ここ数日の仕事はいくつかのJSのよくある応用に関連して、ここでまとめて、時々の需要に備えます.
1.Js操作float型数値加減問題(直接演算は精度の問題がある)
適用:
var a = 12.23;//float型数値
var b = 58.62;//float型数値
alert(a.add(b));
alert(b.sub(a));
toFixedメソッドを使用して小数点を切り取った後、数桁保持します.
2.取得2日間隔日数
PS:个人的にはこの方法がいいと思います.前のブログの绍介PHP日付比較取得日数に比べて、进歩です.ほほほ!
1.Js操作float型数値加減問題(直接演算は精度の問題がある)
// float 10 n (n ), float
Number.prototype.getB = function(){
var arr = this.toString().split('.');
return arr[1]? arr[1].length : 0;
}
Number.prototype.getP = function(to){
return Math.pow(10, Math.max(this.getB(), to.getB()));
}
Number.prototype.add = function(to){
var p = this.getP(to);
return (this * p + to * p) / p;
}
Number.prototype.sub = function(to){
var p = this.getP(to);
return (this * p - to * p) / p;
}
適用:
var a = 12.23;//float型数値
var b = 58.62;//float型数値
alert(a.add(b));
alert(b.sub(a));
toFixedメソッドを使用して小数点を切り取った後、数桁保持します.
2.取得2日間隔日数
/**
*
*
* @param string s
* @param string e
*/
function interval(startDate, endDate){
var d1 = new Date(startDate.replace(/-/g, "/"));
var d2 = new Date(endDate.replace(/-/g, "/"));
var time = d2.getTime() - d1.getTime();
return parseInt(time / (1000 * 60 * 60 * 24));
}
PS:个人的にはこの方法がいいと思います.前のブログの绍介PHP日付比較取得日数に比べて、进歩です.ほほほ!