1

I have a number

num = 0.99922312

I would like to shorten it to just 0.99. I thought I could do this with a simple toFixed

num.toFixed(2)

However this just returns the value of 1.00. I've also tried a bunch of decimal combinations such as .toFixed(2.2) and so on.

Can anyone point me in the right direction please?

alienbuild
  • 246
  • 2
  • 15
  • Kind of I guess but seems such a backwards way. I would need to convert the number to a string, slice it, and then back to a number again? Fair dos. Thanks for your advice. – alienbuild May 19 '20 at 21:32
  • `toFixed` creates a string too. Why are you truncating it if not for purposes of displaying it? Only thing that comes to mind is currency calculations but you should be using a specialized library for that. – John Montgomery May 19 '20 at 21:33
  • @JohnMontgomery Thanks, I didn't actually realise that toFixed also created a string. It's tensorflow prediction results that I'm getting from the back end and then sorting in react front end by the prediction number. The number is also displayed. – alienbuild May 19 '20 at 21:35
  • @alienbuild Does my answer work for you? – Unmitigated May 21 '20 at 00:07

2 Answers2

0

This is the easiest way:

var num = 0.99922312
var twoDecimals = num.toString().substring(0, 4)
console.log(twoDecimals)
Pablo CG
  • 818
  • 6
  • 18
0

You can simply convert the number to a string, get the index of the decimal point, and use slice to remove all the characters after the first two characters after the decimal point.

function truncate(num){
    var str = num.toString();
    var idx = str.indexOf('.');
    return idx != -1 ? str.slice(0, idx + 3): str;
}
console.log(0.99922312, "->", truncate(0.99922312));
console.log(0.8, "->", truncate(0.8));
console.log(0.121, "->", truncate(0.121));
console.log(0.235, "->", truncate(0.235));
console.log(12, "->", truncate(12));

If you need the truncated result as a number instead of a string, you can use the unary plus operator to convert it back to a number.

var truncatedNum = +truncate(num);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80