Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round variable in Javascript Google Spreadsheet

I am querying a Google Spreadsheet and the number I am getting is blowing up some weighting I am doing further down in the code.

My query:

function queryValue3(met1,met2,met3) {
var query3 = new google.visualization.Query('https://spreadsheets.google.com/spreadsheet/tq?range=B7:B9&key=my_key&gid=10');
query3.send(function (response) {
    if (response.isError()) {
        alert('Error in query3: ' + response.getMessage() + ' ' + response.getDetailedMessage());
        return;
    }

    var data3 = response.getDataTable();

    var m1 = data3.getValue(0, 0);
    var m2 = data3.getValue(1, 0);
    var m3 = data3.getValue(2, 0);

The number I'm pulling for m2 is apparently 25.3333333333333323 and is blowing me up later in the function. As long as my numbers are rounded to the 10th or 100th (in this case I want 10th) the function works fine. I using the custom round (1 decimal) and it looks correct in the sheet but the query is grabbing the raw number? In most cases my number is whole and I want it to not have a decimal in those instances. Can someone help me modify the variable m1, m2, and m3 for this case?

Thanks...

like image 523
Dave Lalande Avatar asked Jul 04 '26 08:07

Dave Lalande


1 Answers

There is n.toFixed(2);

You can use it to set the amount of numbers after the decimal.

Example:

foo = 25.3333333333;
foo = +foo.toFixed(2); 
// The plus makes it a number-type again, as toFixed converts to string.
console.log(foo); // 25.33

Edit: Decimal rounding occurs as an expected side-effect:

foo = 25.127;
foo = +foo.toFixed(2); 
console.log(foo); // 25.13

Whole numbers are left the same:

foo = 23;
foo = +foo.toFixed(2);
console.log(foo); // 23
like image 168
Spencer Lockhart Avatar answered Jul 07 '26 23:07

Spencer Lockhart