convert value to 2 decimal places in JS

0

I have the following script:

var x = "202101000000";
var y = 0;


//bilhao

if(x.length >= 10 && x.length <= 12){
	if (x.length == 10){
		y = x.substr(0,1);
	}else if(x.length == 11){
		y = x.substr(0,2);
	}else if(x.length == 12){
		y = x.substr(0,3);
	}
  if(y.length == 1){
  	document.getElementById('totalneuro').innerHTML = y + ' bilhão';
  }else{
  	document.getElementById('totalneuro').innerHTML = y + ' bilhões';
  }
}
<div id="totalneuro"></div>

It happens that it gives me as a result of the value, the number "202 billion", when I would like the value to come with 2 decimal places, in this case, "202.10 billion." How could I solve this? If anyone knows how to make this code smaller and can help me, thank you!

    
asked by anonymous 07.12.2017 / 14:27

3 answers

2

You are giving substr to the value of x , taking only the first three houses of String of 202101000000 . If you want to add the decimal places, you must enter a comma and the rest of the houses at the limit of 2 after this check:

var x = "202101000000";
var y = 0;


//bilhao

if(x.length >= 10 && x.length <= 12){
	if (x.length == 10){
		y = x.substr(0,1) + "," + x.substr(1, 2);
	}else if(x.length == 11){
		y = x.substr(0,2) + "," + x.substr(2, 2);
	}else if(x.length == 12){
		y = x.substr(0,3) + "," + x.substr(3, 2);
	}
  if(y.length == 1){
  	document.getElementById('totalneuro').innerHTML = y + ' bilhão';
  }else{
  	document.getElementById('totalneuro').innerHTML = y + ' bilhões';
  }
}
<div id="totalneuro"></div>
    
07.12.2017 / 14:37
0

You could manipulate the value as a number, rather than a String . Example:

var numero = Number("22101000000");
if(numero >= 1000000000 && numero < 1000000000000) {
    var numeroReduzido = Math.floor(numero / 10000000) / 100;
    var textoFinal = numeroReduzido.toFixed(2).replace(".", ",") + (numero >= 2000000000 ? " bilhões" : " bilhão");
    document.getElementById('totalneuro').innerHTML = textoFinal;
}
    
07.12.2017 / 15:28
0

I was able to do with the following code:

let x = '3710000000';


    function format(num){
      if(num < 1000)
        return num.toString();
      if(num < Math.pow(10,6))
        return (num / 1000).toFixed(2) + " k";
      if(num < Math.pow(10,9))
        return (num / 1000000).toFixed(2) + " Mi";
      if (num < Math.pow(10,12))
        return (num / 1000000000).toFixed(2) + " Bi";
      return (num / Math.pow(10,12).toFixed(2) + " Tri") 
    }
    
    document.getElementById('totalneuro').innerHTML = format(x);
    
13.12.2017 / 21:42