Skip to content Skip to sidebar Skip to footer

Save Integer As Float

function prec(numb){ var numb_string = numb.toString().split('.') return numb_string[(numb_string.length - 1)].length } function randy(minimum, maximum) { var most_acc

Solution 1:

There is a clever way to solve this problem , is to define a class that helps you managing the number values and the decimal values.

functionHappyNumber()
{
    this.value = (typeof(arguments[0]) == "number") ? arguments[0] : 0;
    this.decimal = (typeof(arguments[1]) == "number") ? arguments[1] : 0;
    this.Val = function()
    {
        returnparseFloat(this.value.toFixed(this.decimal));
    }
    this.toString = function()
    {
        return (this.value.toFixed(this.decimal)).toString();
    }
}

How this class works

Now first thing to do is to create a new number like this

var Num = HappyNumber(4.123545,3); 
// first argument is the value // and second one is decimal

To get the value of your variable, you should use the function Val like this

console.log(Num.Val()); // this one prints 4.123 on your console

The most important part is this one, when you use the toString function it return your number

Num.toString() // it returns "4.123"
(new HappyNumber(4,4)).toString(); // it returns "4.0000"

Now you pass arguments as (HappyNumber), and inside your function use toString and it returns the right value you need and it works with numbers like 1.00 2.000 4.00000

Solution 2:

This will do what you want. (Warning: This is probably not a good idea.)

Number.prototype.toString = function () { returnthis.toFixed(1); }

Post a Comment for "Save Integer As Float"