How do I pass this string in number to compute in another array?

Asked

Viewed 33 times

0

<script type="text/javascript">

var alunos = new Array();

alunos[0] = new Array();
alunos[0] [0] = "Aline dos Santos";
alunos[0] [1] = "6,5";
alunos[0] [2] = "2,9";

alunos[1] = new Array();
alunos[1] [0] = "Bianca da Silva";
alunos[1] [1] = "7,8";
alunos[1] [2] = "8,6";

var medias = new Array();

medias[0]=((alunos[0][1]+2)*alunos[0][2]/3);

alert(medias[0]);

</script>

2 answers

2

Utilize parseFloat of to convert from text to number, example:

var alunos = new Array();

alunos[0] = new Array();
alunos[0] [0] = "Aline dos Santos";
alunos[0] [1] = "6,5";
alunos[0] [2] = "2,9";

alunos[1] = new Array();
alunos[1] [0] = "Bianca da Silva";
alunos[1] [1] = "7,8";
alunos[1] [2] = "8,6";

var medias = new Array();

medias[0]=((parseFloat(alunos[0][1])+2)*parseFloat(alunos[0][2])/3);

alert(medias[0]);

0

When you work with arithmetic operations you have to give some attention to certain points. See:

var alunos = new Array();

alunos[0] = new Array();
alunos[0] [0] = "Aline dos Santos";
alunos[0] [1] = "6,5";
alunos[0] [2] = "2,9";

alunos[1] = new Array();
alunos[1] [0] = "Bianca da Silva";
alunos[1] [1] = "7,8";
alunos[1] [2] = "8,6";

var medias = new Array();

medias[0]=((alunos[0][1]+2)*alunos[0][2]/3);

alert(medias[0]);

Your code is dealing with strings and not numbers. So I ask that for your greater understanding you look further and learn more and more. Little mistakes are meant to grow up or something!

Code working:

var alunos = new Array();

alunos[0] = new Array();
alunos[0] [0] = "Aline dos Santos";
alunos[0] [1] = 6,5; // Retirei aspas
alunos[0] [2] = 2,9; // Retirei aspas

alunos[1] = new Array();
alunos[1] [0] = "Bianca da Silva";
alunos[1] [1] = 7,8; // Retirei aspas
alunos[1] [2] = 8,6; // Retirei aspas

var medias = new Array();

medias[0]=((alunos[0][1]+2)*alunos[0][2]/3);

alert(medias[0]);

Don’t forget to leave the vote (if I helped you)!

Browser other questions tagged

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