JSFiddle - React, Tailwind, and code Playground
by kentaromiura
JavaScript
function R(numberString){
var length = numberString.length
var dotPosition = numberString.indexOf('.')
this.denominatore = 1;
this.value = numberString.replace(/0*\.0*/g, '') -0
if(dotPosition != -1) {
this.denominatore = Math.pow(10, length - dotPosition -1);
}
}
R.prototype.round = function(){
return this.value / this.denominatore
}
R.prototype.add = function(r){
if (! r instanceof R) throw new Error('only instance of R are accepted');
while (r.denominatore > this.denominatore) {
this.value *= 10
this.denominatore *= 10
}
while (this.denominatore > r.denominatore) {
r.value *= 10
r.denominatore *= 10
}
this.value += r.value
return this
}
R.prototype.subtract = function(r){
if (! r instanceof R) throw new Error('only instance of R are accepted');
while (r.denominatore > this.denominatore) {
this.value *= 10
this.denominatore *= 10
}
while(this.denominatore > r.denominatore) {
r.value *= 10
r.denominatore *= 10
}
this.value -= r.value
return this
}
var values =
[1,
10,
0.1,
0.01,
0.1231,
0.0123]
var Rs = values.map(function(x){return new R(''+x)});
Rs.forEach(function(r){
console.log(r, r.round(), r.add(new R('0.55')).round(), r.subtract(new R('0.34')).round())
})
console.log(new R('0.1').add(new R('0.2')).round())