Skip to main content
Ben Nadel at LaunchDarkly Lunch & Learn 2018 (New York, NY) with: Lena Krug and Adam Zimman and Christopher Cosentino and Greg Ratner
Ben Nadel at LaunchDarkly Lunch & Learn 2018 (New York, NY) with: Lena Krug ( @LenaLovesStuff ) Adam Zimman ( @azimman ) Christopher Cosentino ( @chriscosentino ) Greg Ratner ( @GregRatner )

Ask Ben: Moving Decimal Places And Formatting Numbers

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:


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