convert value to 2 decimal places in JS

Asked

Viewed 320 times

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 occurs 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? In case someone knows how to make this code smaller and can help me, I appreciate!

3 answers

1

You’re giving substr in the value of x, taking only the first three houses of the String of 202101000000. If you want to add decimals, you should insert a comma and the rest of the boxes in the 2 limit 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>

0

I managed to do it 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);

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;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.