Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Mick79's avatar

Math.round not always working.

I am making an Ajax call and passing through the time value from a currently playing track. In order to simply add an integer to the database rather than a time such as 242.14835735 I am using math.round. Here is the code:

  $.ajax({
                type: 'POST',
                url: '/updatetimelistened',
                data: {
                    trackID: {{$item->track_id}},
                    track: "{{$item->track_name}}",
                    token: "{{$app->token}}",
                    songbox: "{{$app->songbox}}",
                    user_id: "{{$app->user_id}}",
                    time: Math.round(time)
                }
            });

This process runs thousands of times a day but I am getting infrequent errors; maybe 100 a day where the non rounded integer is passed to the controller.

I’m no JavaScript expert - is this just to be expected that sometimes the math.round won’t take effect?

Any insight appreciated.

Here is the error in full

SQLSTATE[22P02]: Invalid text representation: 7 ERROR:  invalid input syntax for type integer: "242.4043537414966"
CONTEXT:  unnamed portal parameter  = '...' (SQL: insert into "track_times" ("user_id", "track_id", "time_listened", "token", "updated_at", "created_at") values (3445, 19357, 242.4043537414966, lKUA9RHZxgMiKpvPGYeE6ZbWTXX6uLkVIg2EP2xZqL7wA0YJgE, 2022-11-30 15:03:03, 2022-11-30 15:03:03) returning "id")
0 likes
6 replies
Tray2's avatar

JavaScript waits for nobody, so my guess is that the time value has not received it's value yet .

You should probably use a promise to make sure that you have a value before proceeding.

I like to use async await for such.

async function calculateResponse() {
	let response = await someSloowRunningFunctionCall();
	if (response.time != undefined) {
		Math.round(time);
	} 
}
Mick79's avatar

@Tray2 Ok, but... the time is being passed. It's just not being rounded. Like it's getting passed as 242.755656575.

jlrdw's avatar

@Mick79 why are you rounding time to an integer, why not use as is.

Mick79's avatar

@jlrdw Well when you put it like that.... lol

Simply because my DB field is an integer type. I convert this to minutes and seconds and display it back to the user. Do you reckon I should just change the column to float and can the rounding?

click's avatar

Why don't you make sure it is an integer before saving it to the database? Always follow the rule "never trust your user / front end". The same might apply for passing the user_id ? Can I change this to anyone else user id and it will be stored in your db?

1 like

Please or to participate in this conversation.