-1

I was searching a way to only display two decimals of a variable and I found the .toFixed() function, but it rounds the final number, I came across this page Display two decimal places, no rounding, where one guy says about this method: .toString().match(/^-?\d+(?:\.\d{0,2})?/)[0], which works perfectly fine, but it's too long. I tryed doing this:

function twoDecimals(i) {
i = Number(i.toString().match(/^-?\d+(?:\.\d{0,2})?/)[0]);
}

.toString() makes it a string, so I use Number() to make it back a variable

and then I do this:

var num = 12.34567;
num.twoDecimals(this);

Basically I want to make .twoDecimals() equal to .toString().match(/^-?\d+(?:\.\d{0,2})?/)[0] or even better if it has Number() surrounding all

Community
  • 1
  • 1
  • You can't assign to the caller's variable from a function call. – SLaks Dec 04 '16 at 00:20
  • 1
    "...but it's too long" what makes you say it's too long? Is there a tax on the number of characters you can use? Are you attempting to participate in a code golf? Shortening code beyond the point of readability is a sure fire way to make sure that future you won't have a clue what past you was trying to do. – zzzzBov Dec 04 '16 at 03:40

2 Answers2

1

Try doing

Number.prototype.twoDecimals = function(arg){
    return arg.toString().match(/^-?\d+(?:\.\d{0,2})?/)
}

This should give all objects of the Number class a new method called twoDecimals.

Max
  • 1,325
  • 9
  • 20
0

How about this

Number.prototype.twoDecimals = function(){
    return (Number)(this.toString().match(/^-?\d+(?:\.\d{0,2})?/));
}
var num = 12.34567;
console.log(num.twoDecimals()); // Print out 12.34
  • I recommend you should read about javascript prototype. For example : https://www.pluralsight.com/blog/software-development/understanding-javascript-prototypes – Thanh Phan Truong Dec 05 '16 at 15:24