0

I have a column called Odo that contains the number of meters in a trip. I would normally divide that by 1000 to display the number of Km's.

The line of code in question:

convert(varchar(10), startPos.Distance / 1000)

causes the following error

Msg 8115, Level 16, State 8, Procedure sp_report_select_trip_start_and_stop, Line 7 [Batch Start Line 2]
Arithmetic overflow error converting numeric to data type numeric.

Msg 232, Level 16, State 2, Procedure sp_report_select_trip_start_and_stop, Line 9 [Batch Start Line 2]
Arithmetic overflow error for type varchar, value = 931.785156.

That number is clearly longer than my varchar. How do I divide, truncate to 1 decimal place and then convert?

Edit: SQL Server 2008 R2, so format() is not available

3

1 Answer 1

1

You can use format

format(startPos.Distance/1000,  '#,###,###.#')

Or,

convert(varchar(10),cast(startPos.Distance/1000 as decimal(9,1)))

You may wish to introduce round() into these as well. e.g.

format(round(startPos.Distance/1000,1),  '#,###,###.#')

or

convert(varchar(10),cast(round(startPos.Distance/1000,1) as decimal(9,1)))
Sign up to request clarification or add additional context in comments.

3 Comments

2008r2 so no format() function available same result, using cast or convert.
"Same result" ... to what?
I apologise. I tested again in a clean window and the last option (with round()) is perfect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.