js 常用計算

2021-09-13 00:18:48 字數 1052 閱讀 5793

由於存在計算精度的問題,例如0.1+0.2 = 0.30000000000000004,所以需要整理以下方法,方便進行簡單計算。

主要思路是先轉成整數,然後再進行計算,計算完再轉回浮點數

獲取小數字以及向右移動小數字,是計算時轉換成整數的工具函式。加減乘除四個函式都用到了
// 獲取小數字

export function getdecimalplace(num) catch (e)

}

/**

* 向右移動小數點

* @param moveplace 移動步數,正向右,負數向左

*/export function movedecimalplace(num, moveplace) else if (step < 0) else

}

這裡右移動小數點需要先轉成整形,再進一步處理是因為存在一些浮點數乘以 10 的倍數也會出問題!

例如:268.34*100 => 26833.999999999996

/**

* 相加 arg1 + arg2

*/export function add(arg1, arg2)

/**

* 相減 arg1 - arg2

*/export function sub(arg1, arg2)

/**

* 乘法 arg1 * arg2

*/export function multiply(arg1, arg2)

return arg1 * arg2;

}

/**

* 除法 arg1 / arg2

*/export function division(arg1, arg2)

原始碼鏈結

更多**片段

個人部落格鏈結

js常用計算方法整理

一 除法取整 math.round x 四捨五入,如math.round 0.60 結果為1 math.round 0.49 結果為0 math.floor x 向下捨入,如math.floor 0.60 與math.floor 0.49 結果均為0 math.ceil x 向上捨入,如math.c...

Oracle 常用計算

時間計算 oracle 兩個時間相減預設的是天數 oracle 兩個時間相減預設的是天數 24 為相差的小時數 oracle 兩個時間相減預設的是天數 24 60 為相差的分鐘數 oracle 兩個時間相減預設的是天數 24 60 60 為相差的秒數 months between date2,dat...

Oracle 常用計算

時間計算 oracle兩個時間相減預設的是天數 oracle 兩個時間相減預設的是天數 24 為相差的小時數 oracle 兩個時間相減預設的是天數 24 60 為相差的分鐘數 oracle 兩個時間相減預設的是天數 24 60 60 為相差的秒數 months between date2,date...