Skip to main content
Ben Nadel at cf.Objective() 2010 (Minneapolis, MN) with: Doug Hughes and Ezra Parker and Dan Wilson and John Mason and Jason Dean and Luis Majano and Mark Mandel and Brian Kotek and Wil Genovese and Rob Brooks-Bilson and Andy Matthews and Simeon Bateman and Ray Camden and Chris Rockett and Joe Bernard and Dan Skaggs and Byron Raines and Barney Boisvert and Simon Free and Steve 'Cutter' Blades and Seth Bienek and Katie Bienek and Jeff Coughlin
Ben Nadel at cf.Objective() 2010 (Minneapolis, MN) with: Doug Hughes Ezra Parker Dan Wilson John Mason Jason Dean Luis Majano Mark Mandel Brian Kotek Wil Genovese Rob Brooks-Bilson Andy Matthews Simeon Bateman Ray Camden Chris Rockett Joe Bernard Dan Skaggs Byron Raines Barney Boisvert Simon Free Steve 'Cutter' Blades Seth Bienek Katie Bienek Jeff Coughlin

Ask Ben: Moving Decimal Places And Formatting Numbers

By
Published in , Comments (3)

Hi Ben, I have been trying to use DecimalFormat and NumberFormat to get some integers coming out of a database query to display as decimals numbers. For Example I want 415 to display as 4.15. I also need 6 to display as .60 How might I accomplish this. I really love your writings by the way.

To do this, all you need to do is move over the decimal place and then format the number. Based on those two numbers, it looks like the number of decimal places is not generic. For 415, you want to move it over twice. For 6, you only move it over once. You'll have to figure out that part of the logic, but once you do, the formatting is quite easy:

<!--- Set both values so that we can mimic database values. --->
<cfset intValueA = 415 />
<cfset intValueB = 6 />


<!--- Output first number in decimal format. --->
#DecimalFormat( intValueA / 100 )#<br />


<!---
	The second number is slightly more tricky since you did not
	want a leading zero. All of the number formatting options put
	in a leading zero. Therefore, we have to manually remove that
	with some list functionality.
--->
.#ListLast( DecimalFormat( intValueB / 10 ), "." )#

Once of the beauties of a base-10 number system such as ours is that all you need to do to move decimal places is divide by a power of 10. Each power of 10 moves the decimal place over once. Running the above code we get the following output:

4.15
.60

Hope that helps.

Want to use code from this post? Check out the license.

Reader Comments

I believe in love. I believe in compassion. I believe in human rights. I believe that we can afford to give more of these gifts to the world around us because it costs us nothing to be decent and kind and understanding. And, I want you to know that when you land on this site, you are accepted for who you are, no matter how you identify, what truths you live, or whatever kind of goofy shit makes you feel alive! Rock on with your bad self!
Ben Nadel
Managed hosting services provided by:
xByte Cloud Logo