天天看點

javascript(js)中使用BigDecimal

了解了java中使用BigDecimal之後改在javascript上使用BigDecimal

javascript上使用BigDecimal 與java中使用還是有很大差別的

定義BigDecimal類型

var x = new BigDecimal();
此時的 x相當于一個空的BigDecimal類型的資料
           

将資料改為BigDecimal類型

如修改 var x = 1;
相當于将x的值重新定義在指派給x
x =  new BigDecimal(""+x);
           

多加注意

new BigDecimal(); 括号中隻能是字元串類型的數字如果是變量 參考我寫的方式(“”+x)

js中的BigDecimal方法與java中的還是有一些差別的

常用的加減乘除是相同的

java中一些擴充方法在js中無法使用 也有可能是我在網上找的js檔案不齊全造成的

如上一篇 java中用到的

除 這個方法:x.divide();

js中就隻有除法運算的功能 java中有擴充的參數進行一些其他操作

js中BigDecimal的四舍五入

使用的方法

x.setScale(10, BigDecimal.ROUND_HALF_DOWN);
其中10表示保留小數位數
BigDecimal.ROUND_HALF_DOWN表示四舍五入的規則
           

其他四舍五入規則

ROUND_CEILING 
    Rounding mode to round towards positive infinity. 
     向正無窮方向舍入

    ROUND_DOWN 
    Rounding mode to round towards zero. 
     向零方向舍入

    ROUND_FLOOR 
    Rounding mode to round towards negative infinity. 
     向負無窮方向舍入

    ROUND_HALF_DOWN 
    Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round down. 
     向(距離)最近的一邊舍入,除非兩邊(的距離)是相等,如果是這樣,向下舍入, 例如1.55 保留一位小數結果為1.5

    ROUND_HALF_EVEN 
    Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor. 
     向(距離)最近的一邊舍入,除非兩邊(的距離)是相等,如果是這樣,如果保留位上的數字是奇數,使用ROUND_HALF_UP ,如果是偶數,使用ROUND_HALF_DOWN

    ROUND_HALF_UP 
    Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up. 
     向(距離)最近的一邊舍入,除非兩邊(的距離)是相等,如果是這樣,向上舍入, 1.55保留一位小數結果為1.6

    ROUND_UNNECESSARY 
    Rounding mode to assert that the requested operation has an exact result, hence no rounding is necessary. 
     計算結果是精确的,不需要舍入模式

    ROUND_UP 
    Rounding mode to round away from zero. 
      向遠離0的方向舍入

           

如有錯誤望指正 謝謝

BigDecimal.js檔案:我使用的

網上找的大佬的 點選跳轉