How to convert a string representation of a number to a number in coldfusion?
Asked Answered
A

2

26

I want to be able to convert a string number such as "1,427.76" to a number in coldfusion but the comma is making it fail. Is there a simple way to do it besides having to remove the comma?

<cfset string = "1,427.75">

<cfset number = string * 100>

The error occurs when trying to perform mathematical operations on it. If the comma is removed it works just fine but I'm getting the comma from a database calculation.

Autoradiograph answered 25/1, 2010 at 17:11 Comment(0)
E
53

I know you can use LSParseNumber:

<cfset string = "1,427.75">

<cfset number = LSParseNumber(string) * 100>
Estrous answered 25/1, 2010 at 17:24 Comment(1)
@Scott Chantry if derivation's answer worked for you, don't forget to choose it as the Accepted answer. :)Minx
P
10

Val() works as well for simple conversions where you don't care about locale, e.g. Val('123.45')

Phenyl answered 26/3, 2011 at 0:39 Comment(3)
easy fixed with a string = val( string.replaceAll('[^0-9\.]+','') );Beading
using val() is roughly 2x faster than lsParseNumber()Beading
even faster to use string = ( string.replaceAll('[^0-9\.]+', '') * 1 );Beading

© 2022 - 2024 — McMap. All rights reserved.