1

寻找一种一致的方式来编写(或扩展)解析器来做数学方程。我大部分时间都在使用mathjs,效果很好。但它不处理百分比。我正在尝试编写规则来处理将百分比添加到百分比,将百分比添加到非百分比等。

1 + 6 + 7% = 7.49 – 正确。
1 + 6 + 7% = 7.07 – 不正确。

56.47 + 15% = 64.9405 – 正确。
56.47 + 15% = 56.62 – 不正确。

ETC..

欢迎任何提示或建议。

4

1 回答 1

1

你可以这样做:

      Number.prototype.plusPecentage = function(n){    
        return this+(this*n/100);
      }
    
      console.log((1 + 6).plusPecentage(7))

或这个:

Math.plusPecentage = function(n,p){
  return n+(n*p/100);
}

console.log(Math.plusPecentage(7,7))

你也可以做同样的事情,但扩展mathjs库做math.plusPecentage = function () {//code}

于 2018-07-29T22:09:53.163 回答