JSFiddle - React, Tailwind, and code Playground
by NickU
JavaScript
function GetFloat(str)
{
if (typeof str === 'string')
{
var i, out = ""; // replace this
if (str == "")
return 0.0;
for (i = 0; i < str.length; i++)
{
var chr = str.charAt(i);
if ((chr >= "0" && chr <= "9") || chr == '.' || chr == 'e')
{
out += chr;
}
else if (chr == "(" || chr == "-")
{
out += "-";
}
}
if (out == "")
return 0.0;
return parseFloat(out);
}
else
return parseFloat(str);
}
class RoundedNumber extends Number {
constructor(v, precision) {
super(v );
this.precision = precision;
}
}
RoundedNumber.prototype[Symbol.toPrimitive] = function(hint) {
var result;
switch (hint) {
case 'string':
result = "a:" + this.valueOf().toFixed(this.precision);
break;
case 'number':
result = Math.round(this.valueOf() * this.precision) / this.precision;
break;
case 'default':
result = this.valueOf();
break;
}
return result;
}
RoundedNumber.prototype[Symbol.toPrimitive] = function(hint) {
var result;
switch (hint) {
case 'string':
result = "a:" + this.valueOf().toFixed(this.precision);
break;
case 'number':
result = Math.round(this.valueOf() * this.precision) / this.precision;
break;
case 'default':
result = this.valueOf();
break;
}
return result;
}
var num1 = new RoundedNumber(1e-8,9);
var num2 = new RoundedNumber(12123123133.456789,8);
console.log(num1.toString()); // "a:0.000000010"
console.log(num2.toString()); // "a:12123123133.45678902"
var adds = new RoundedNumber(num1 + num2, 8);
console.log(adds.toString()); // "a:12123123133.45678902"
console.log(num1.toString()); //...