Parsing formatted String to Int
How can I parse formatted string to Integer ?
I have a formated string like this $900,000 and I need to convert it to 900000 so I could do calculations with it.
I tried something like this
NumberFormat nf = NumberFormat.getIntegerInstance(request.getLocale());
ttlMargin=nf.parse(screenVal);I got this exception
"java.lang.NumberFormatException: For input string: "$1,050,000""
I am working on the JSP file that provides
margins,sales etc. I am reading this data off the
screen where it is beeing displayed according to the
accounting practices.
That's why I get it as a formatted string and why I
am trying covert that string to the numberScreen-scraping is a problematic, bad design. It sounds like what you really want is to call a web service which returns its results as data that a program can understand (XML, for example), not HTML (which is meant more for humans to read). I know, you probably can't change the design at this point... just food for thought. In the meantime, you'll probably have to manually parse those strings yourself by stripping out the '$' and ',' characters and then use parseInt on the result.
Similar Messages
-
Problem formatting string with ints
I'm trying to perform simple string formatting using a resource file but I'm having problems when I pass integers to the format argument.
Here is the line of code that causes the IllegalFormatConversionException:
ResourceFile.getFormattedString("XMLGAME",myBounds.getWidth(),myBounds.getHeight())//myBounds.getWidth() and myBounds.getHeight() return intsHere is the method in ResourceFile:
public static String getFormattedString(String resource, int... args)
return String.format(resourceFile.getString(resource), args);
}And here is the string in the properties file
XMLGAME <game name="game" width="%d" height="%d">\nEdited by: JFactor2004 on Dec 3, 2008 10:15 PMInstead of {color:000080}int{color}..., declare "args" the same way format() does, as Object...: public static String getFormattedString(String resource, Object... args) The way you're doing it would require the {color:000080}int{color}[] to be "bulk-autoboxed" to an Integer[] or Object[], and Java can't do that. Instead, it treats "args" as an Object[] containing one element, which happens to be an {color:000080}int{color}[].
-
in my C# project I have an array type of String. the array gets numbers from type int.
int numCell;
string[] arr = new string[numCell];
then i use it in a function like this:
sum += int.Parse(arr[i]);
and it works!
but, when i dothe same thing in WPF it tells me:
Input string was not in a correct format.
what shouuld i do?Why did you mark your own question as answer? Please unmark it.
>>if in C# it worked why wouldn't it work in wpf?
As I have already mentioned, it is because of the actual value of arr[i]. It has nothing to do with Windows Forms or WPF but it is possible that your WPF application has put a different value in the array than your Windows Forms Application did. And if this
specific value is not a valid number the parsing will always fail. So you should check the values that put into the array and probably use the int.TryParse method to do the parsing:
int sum;
if (!int.TryParse(arr[i], out sum))
//the value of arr[i] was NOT a valid number...
This will however not change the fact that for example the value "D1" cannot be converted to an int using the int.Parse or int.TryParse method.
Please remember to close your threads by marking helpful posts as answer and please start a new thread if you have a new question. -
Hi All,
I have a string field that is formatted in XML format. What I want to be able to do is pull a specific element from the xml formatted string.
Example string:
<customer><name>john</name><id>25636</id></customer>
I want to retreive just the id number of 25636 from this string.
I would I go about accomplishing this?
Thank you in advance,I fixed it on my own.
Here' s my answer for others that may need it:
if(instr({field.xmlstring},'</id>') - instr({field.xmlstring},'<id>') = 7)then
mid(totext({field.xmlstring}),instr({field.xmlstring},'<id>')+4,3)
else if(instr({field.xmlstring},'</id>') - instr({field.xmlstring},'<id>') = 8)then
mid(totext({field.xmlstring}),instr({field.xmlstring},'<id>')+4,4)
else if(instr({field.xmlstring},'</id>') - instr({field.xmlstring},'<id>') = 9)then
mid(totext({field.xmlstring}),instr({field.xmlstring},'<id>')+4,5)
I use the conditions to cover all possible lengths of the id number. -
Help regarding parsing the string
I wanted to display diffrent colored strings in the Textarea which is not possible. But from somewhere I came to know that it is possible by parsing the strings comming frm various sources and then display them with diffrent colors. can anyone help me out regarding this. The format is something like:
&x100100100This is a colored string!&n
the &x100100100 means that the text after it should use RGB value of 100,100,100. &n meant that the colors should stop and return to default.
Well... this makes the client need to parse strings and set colors etc
Can anyone explain me with some small code without using the swing class. thanks in advance.Here is my code I am trying to do...Pls see to it and tell me the mistake....
import java.net.*;
import java.applet.*;
import java.awt.*;
import java.io.*;
import java.awt.event.*;
import java.util.*;
import java.lang.*;
public class client extends Applet
//implements KeyListener
TextArea display;
//TextField send;
TextArea send;
Label status;
Color color;
mypanel p1;
boolean connected=false;
private Socket sock;
protected BufferedReader instream;
private DataOutputStream out;
private String IP;
private int port;
Thread reader;
private String fontName;
private int fontSize;
private String company;
private String userName;
private String userID;
private String compName;
public void start()
String param;
String mStr ;
IP=getParameter("IP");
userID=getParameter("userID");
userName=getParameter("userName");
fontName=getParameter("fontName");
company=getParameter("company");
mStr=userID+"#"+userName+"#US#"+company+"#1#A";
param=getParameter("fontSize");
try{
if (param!=null)
fontSize=Integer.parseInt(param);
else
fontSize=0;
} catch (NumberFormatException e){
fontSize=-1;
param=getParameter("port");
try{
if (param!=null)
port=Integer.parseInt(param);
else
port=2;
} catch (NumberFormatException e){
port=-1;
//display.append(sock.getURL());
connect(IP,port,mStr);
public void init()
setBackground(Color.white);
//color = new Color(221,240,255);
setForeground(Color.black);
p1=new mypanel();
add(p1);
reader = new readMessage(this);
reader.setPriority(1);
//send.addKeyListener(this);
public void paint(Graphics g){
String s;
double p;
int i;
//status.setBackground(Color.blue);
g.setColor(color);
display.setEditable(false);
status.setForeground(Color.black);
display.setBackground(Color.white);
p1.cmdSend.setBackground(Color.white);
p1.cmdSend.setForeground(Color.black);
display.setFont(new Font("Arial", Font.PLAIN, 11));
//status.setBackground(Color.blue);
display.setForeground(Color.blue);
public void connect(String host,int p,String mStr)
try{
sock=new Socket(host,p);
instream = new BufferedReader( new InputStreamReader(sock.getInputStream()));
out = new DataOutputStream(new BufferedOutputStream(sock.getOutputStream()));
out.writeBytes(mStr);
connected=true;
out.flush();
reader.start();
setStatus("You are Connected Successfully. ");
display.append("Welcome to "+company+" chat . A Customer Support Executive will assist you shortly.\n");
catch (UnknownHostException a) {
connected=false;
p1.cmdSend.setEnabled(false);
send.setEditable(false);
display.append(company+" live support service fails due to some technical reason.");
//status.setText("Intelecorp Live Suport service fails due to some technical reasions.");
catch (IOException b) {
connected=false;
p1.cmdSend.setEnabled(false);
send.setEditable(false);
display.append(company+" live support service fails due to some technical reason.");
//status.setText("Intelecorp Live Suport service fails due to some technical reasions.");
catch (SecurityException c ) {
connected = false;
display.append("Error");
public void setStatus(String mstr)
status.setText(mstr);
public boolean action (Event e, Object arg)
if(e.target instanceof Button)
if (e.target==p1.cmdSend)
sendMessage(send.getText());
send.setText("");
return true;
return false;
public boolean keyUp(Event e, int key)
if(key==Event.ENTER)
sendMessage(send.getText());
send.setText("");
return true;
return false;
public void keyPressed(KeyEvent e)
switch (e.getKeyCode()) {
case KeyEvent.VK_ENTER:
sendMessage(send.getText());
send.setText("");
break;
default:
break;
return ;
public void keyReleased(KeyEvent e) {} ;
public void keyTyped(KeyEvent e) {} ;
public void sendMessage(String mStr)
int mflag;
try{
mflag=mStr.lastIndexOf('\n');
mStr.trim();
if ((connected==true) && (mStr.length()>0))
if (mflag<0)
mStr=mStr+"\n";
display.append(userName+" : "+"&x100100100"+mStr+"!&n");
out.writeBytes(mStr);
out.flush();
send.setText("");
}catch (IOException e){
connected=false;
p1.cmdSend.setEnabled(false);
send.setEditable(false);
display.append("Unable to send the message, you may be disconnected from the server.");
//status.setText("Unable to send the message, you may disconnected from the server.");
public void destroy(){
try{
sock.close();
}catch (IOException e){
status.setText(e.toString());
class readMessage extends Thread{
client mClient;
private String mStr;
public readMessage(client c){
super("Client Reader");
this.mClient = c;
public void run()
mStr=null;
try{
if (connected==true)
while(true)
mStr = instream.readLine();
display.append("&x200200200"+mStr+"!&n"+"\n");
//display.setText(display.getText()+"\n"+mStr);
if (mStr==null)
break;
}catch (IOException e){
connected=false;
p1.cmdSend.setEnabled(false);
send.setEditable(false);
display.append("Unable to read the messages, you may be disconnected from the server.");
//status.setText("Unable to read the messages, you may disconnected from the server.");
class mypanel extends Panel
Label l1,l2,l3;
Button cmdSend;
mypanel()
setLayout(new BorderLayout());
add("North",display=new TextArea("",12,50,TextArea.SCROLLBARS_VERTICAL_ONLY));
add("West",send=new TextArea("",2,50,TextArea.SCROLLBARS_VERTICAL_ONLY));
//add("West",send=new TextField());
add("East",cmdSend=new Button(" Send "));
add("South",status=new Label(""));
} -
Date from a string and int value in ssis
hi so my table is as follows
active expirymonth
expiryyear
0 October 2014
0 February 2015
1 January 2012
and so on
now my requirement is that if active =0 then in a new table lets say LASTDATE and they want a date with the last day of the expiry month and year and if active is anything else write NULL for eg
LASTDATE
10/31/2014
02/28/2015
NULL
I went to derived tables and made a new table called lastdate. What expression do i build in the expression builder to get the required result as i could not find a way to convert the text into int and then into a dateHi Bharatb111,
If you want to achieve this using Derived Columns transform, you have to use following expression to first convert the month name value to integer:
([expirymonth]==”January”)?1:([expirymonth]==“February”)?2: ([expirymonth]==”March”)?3:([expirymonth]==“April”)?4:5
However, if we need to validate a couple of or even all of twelve months, the expression validation will be failed. So, the Derived Column approach is impossible.
To achieve your goal, you can use a Script Component to perform the date format conversion. This way, we can convert “dd/MMMM/yyyy(such as “01/October/2014”) format string value to “MM/dd/yyyy” (such as “10/01/2014”), and assign this value to a new output
column (assuming its name is “DateVal” and its data type is DT_DATE) of the Script Component. Then, we can drag a Derived Column under the Script Component and connect them. In the Derived Column, we can add a new column named “LASTDATE” with the following
expression:
([active]==0)?DATEADD(“d”,-1, DATEADD(“Month”),1,DateVal]):NULL(DT_DATE)
For the Script Component code snippet, please refer to Reza’s answer:
http://social.msdn.microsoft.com/Forums/sqlserver/en-US/1661339c-252c-4197-9cfd-943e1d86b573/convert-a-string-to-date-format?forum=sqlintegrationservices
Hope this helps.
Regards,
Mike Yin
TechNet Community Support -
How to read a C structure with string and int with a java server using sock
I ve made a C agent returning some information and I want to get them with my java server. I ve settled communication with connected socket but I m only able to read strings.
I want to know how can I read strings and int with the same stream because they are sent at the same time:
C pgm sent structure :
char* chaine1;
char* chaine2;
int nb1;
int nb2;
I want to read this with my java stream I know readline methode to get the first two string but after two readline how should I do to get the two int values ?
Any idea would be a good help...
thanks.
Nicolas (France)Does the server sent the ints in little endian or big endian format?
The class java.io.DataInputStream (with the method readInt()) can be used to read ints as binary from the stream - see if you can use it. -
Hi,
I need to parse,in CVP 7.0(1), the BAAccountNumber variable passed by the ICM dialer. Is there a built-in java class or other function that would help me do this?
Our BAAccountNumber variable looks something like this: 321|XXX12345678|1901|M. In IP IVR I use the "Get ICM Data" object to read the BAAccountNumber variable from ICM and then I use the "token index" feature to parse the variable (picture below).
Alternately, IP IVR also has a Java class that allows me to do this; the class is "java.lang.String" and the method is "public int indexOf(String,int)"
Is there something equivalent in CVP 7.0(1)?
thanksThanks again for your help. This is what I ended up doing:
This configurable action element takes a string seperated by two "|" (123|123456789|12)
and returns 3 string variables.
you can add more output variables by adding to the Setting array below.
// These classes are used by custom configurable elements.
import com.audium.server.session.ActionElementData;
import com.audium.server.voiceElement.ActionElementBase;
import com.audium.server.voiceElement.ElementData;
import com.audium.server.voiceElement.ElementException;
import com.audium.server.voiceElement.ElementInterface;
import com.audium.server.voiceElement.Setting;
import com.audium.server.xml.ActionElementConfig;
public class SOMENAMEHERE extends ActionElementBase implements ElementInterface
* This method is run when the action is visited. From the ActionElementData
* object, the configuration can be obtained.
public void doAction(String name, ActionElementData actionData) throws ElementException
try {
// Get the configuration
ActionElementConfig config = actionData.getActionElementConfig();
//now retrieve each setting value using its 'real' name as defined in the getSettings method above
//each setting is returned as a String type, but can be converted.
String input = config.getSettingValue("input",actionData);
String resultType = config.getSettingValue("resultType",actionData);
String resultEntityID = config.getSettingValue("resultEntityID",actionData);
String resultMemberID = config.getSettingValue("resultMemberID",actionData);
String resultTFNType = config.getSettingValue("resultTFNType",actionData);
//get the substring
//String sub = input.substring(startPos,startPos+numChars);
String[] BAAcctresults = input.split("\\|");
//Now store the substring into either Element or Session data as requested
//and store it into the variable name requested by the Studio developer
if(resultType.equals("Element")){
actionData.setElementData(resultEntityID,BAAcctresults[0]);
actionData.setElementData(resultMemberID,BAAcctresults[1]);
actionData.setElementData(resultTFNType,BAAcctresults[2]);
} else {
actionData.setSessionData(resultEntityID,BAAcctresults[0]);
actionData.setSessionData(resultMemberID,BAAcctresults[1]);
actionData.setSessionData(resultTFNType,BAAcctresults[2]);
actionData.setElementData("status","success");
} catch (Exception e) {
//If anything goes wrong, create Element data 'status' with the value 'failure'
//and return an empty string into the variable requested by the caller
e.printStackTrace();
actionData.setElementData("status","failure");
public String getElementName()
return "MEDDOC PARSER";
public String getDisplayFolderName()
return "SSC Custom";
public String getDescription()
return "This class breaks down the BAAccountNumber";
public Setting[] getSettings() throws ElementException
//You must define the number of settings here
Setting[] settingArray = new Setting[5];
//each setting must specify: real name, display name, description,
//is it required?, can it only appear once?, does it allow substitution?,
//and the type of entry allowed
settingArray[0] = new Setting("input", "Original String",
"This is the string from which to grab a substring.",
true, // It is required
true, // It appears only once
true, // It allows substitution
Setting.STRING);
settingArray[1] = new Setting("resultType", "Result Type",
"Choose where to store result \n" +
"into Element or Session data",
true, // It is required
true, // It appears only once
false, // It does NOT allow substitution
new String[]{"Element","Session"});//pull-down menu
settingArray[1].setDefaultValue("Session");
settingArray[2] = new Setting("resultEntityID", "EntityID",
"Name of variable to hold the result.",
true, // It is required
true, // It appears only once
true, // It allows substitution
Setting.STRING);
settingArray[2].setDefaultValue("EntityID");
settingArray[3] = new Setting("resultMemberID", "MemberID",
"Name of variable to hold the result.",
true, // It is required
true, // It appears only once
true, // It allows substitution
Setting.STRING);
settingArray[3].setDefaultValue("MemberID");
settingArray[4] = new Setting("resultTFNType", "TFNType",
"Name of variable to hold the result.",
true, // It is required
true, // It appears only once
true, // It allows substitution
Setting.STRING);
settingArray[4].setDefaultValue("TFNType");
return settingArray;
public ElementData[] getElementData() throws ElementException
return null; -
Date contructor deprecation : Parsing a String to Date
Hi All,
In Java 1.5 the Date() constructor Date(String s) is deprecated. As per the API Documentation DateFormat.Parse() method is used.
The following code from Java 1.4 version has to be upgraded to Java 1.5.
Existing Code:
Date dDate = new Date(sDate);
Modified Code:
DateFormat df = DateFormat.getDateInstance();
Date dDate = df.parse(sDate);
Here the DateFormat accepts a default formatting style as "Feb 01, 2007" and parses the String.
If the String sDate belongs to any other formatting style such as "01 Feb, 2007" or "01 Feb, 07" the code piece throws unparsable date error.
Please give your thougts on this issue to parse the string of any format..
Thanks,
Rajesh.Hi All,
In Java 1.5 the Date() constructor Date(String s) is
deprecated. As per the API Documentation
DateFormat.Parse() method is used.
The following code from Java 1.4 version has to be
upgraded to Java 1.5.
Existing Code:
Date dDate = new Date(sDate);
Modified Code:
DateFormat df = DateFormat.getDateInstance();
Date dDate = df.parse(sDate);
Here the DateFormat accepts a default formatting
style as "Feb 01, 2007" and parses the String.
If the String sDate belongs to any other formatting
style such as "01 Feb, 2007" or "01 Feb, 07" the code
piece throws unparsable date error.
Please give your thougts on this issue to parse the
string of any format..You can't. What date is this: "08/04/24"? 8 April, 1924? 4 August, 2024?
>
Thanks,
Rajesh. -
I'm writing a program which will utilize the internal memeory of the Agilent 34410A DMM for making fast measurements (10K/s). In order to do this, I need to setup a test, have the data stored to the internal memory, then read and delete it, while other measurements are still happening. The best command for the read/delete function is the R? command, but it returns the data in a strange format which breaks the ViScanf format string.
an example of the R? reading in below:
R? 2
#231+2.87536000E-04,+3.18131400E-03
Is there a way to setup the ViScanf format string to handle this?
Thanks
RyanYes, I am using CVI
If it was just returning one value I would use a simple viScanf function like this:
viScanf (vi, "%f", fbuf);
If you do a READ from in the instrument, it returns an array of floats so you need to adjust you viScan fuction parse the string into an array of floats like this (array of 500 for this example):
viScanf(vi, "%,500f", fbuf);
The problem is the data response to the R? command starts with the array size and is then followed by the data (#231+2.87536000E-04,+3.18131400E-03). In the previous example, I need to delete the #, and parse the 231 into an array size variable and then fill an array (fbuf in this case) with the data. -
Hi,
I'm having a problem with parsing a string. Basically, I want to take a string for example: "TomWentToTheShop" and divide it into a coherent sentence (Tom went to the shop).
I've started the code by breaking the string into a char array, and if the character is a capital then store the index in the array and then do a substring.
But I don't think this is the best way to solve the problem, if anyone has any ideas it would be greatly appreciated.
thanks.
char[] charRequestTypeArray = string.toCharArray();
for (int i = 1; i < (charRequestTypeArray.length -1); i++) {
char c = charRequestTypeArray;
if (Character.isUpperCase(c)) {
Arrays.fill(storeCapitalIndex, i);
else{
Arrays.fill(storeNonCapitalIndex, i);String s = "TomWentToTheShop";
System.out.println(s.charAt(0) + s.substring(1).replaceAll("((?<!^)[A-Z])", " $1").toLowerCase());or even just System.out.println(s.charAt(0) + s.substring(1).replaceAll("([A-Z])", " $1").toLowerCase());Edited by: sabre150 on Nov 11, 2007 9:40 PM -
I'm trying to find an easy way to parse a string like this
String, brand,model, number;
String toParse=(Sony)(VZ-12324)(1);Is there a simple way of parsing the string to the "(" and ")" are omitted and brand=Sony;
model=VZ-12324);
number="1";
???String toParse = "(Sony)(VZ-12324)(1)";
String[] parts = toParse.split("[()]");
String brand = parts[1];
String model = parts[3];
int number = Integer.parseInt(parts[5]);
System.out.println(brand);
System.out.println(model);
System.out.println(number); -
Can somebody tell me the function used to parse a string and how it works? All I want to do is seperate the string 'AG-01' into another string 'AG-' and an int '01'. I have been through numerous resources and have found nothing at all on parsing functions.
This in one way:
String txt = "AG-01";
String first = txt.substring(0,3);
int second = Integer.parseInt(txt.substring(3,5));
%>
First string:<%=first%>
Second int :<%=second%>
Bye
Beck74 -
Error: ORA-01861: literal does not match format string
Hi,
I am doing a RFC-XI-JDBC scenario.
In the CC monitoring , i am getting this error for the reciver CC:
"Error while parsing or executing XML-SQL document: Error processing request in sax parser: Error when executing statement for table/stored proc. "TableNAMe"(structure 'STATEMENTNAME'): java.sql.SQLException: ORA-01861: literal does not match format string "
Please guide me what can be the cause and how to solve it.
Thanks,
PuneetThis is how my payload looks like :
<?xml version="1.0" encoding="UTF-8"?>
<ns1:MT_JDBC_REC xmlns:ns1="https:namespace.scene3">
<STATEMENTNAME>
<TABLE_NAME action="INSERT">
<TABLE>ggclgis</TABLE>
<access>
<VALVE_ID>12584</VALVE_ID>
<EQUNR>122</EQUNR>
<ERNAM>12122</ERNAM>
<INVNR>1212</INVNR>
<GROES>1212</GROES>
<ELIEF>123</ELIEF>
<GWLEN>21-jul-2008</GWLEN>
<GWLDT>12-jun-2006</GWLDT>
<SERGE>wqwqw</SERGE>
<TYPBZ>wqwqwq</TYPBZ>
</access>
</TABLE_NAME>
</STATEMENTNAME>
</ns1:MT_JDBC_REC>
Please tell me if it looks fine. -
Can you parse a string in java?
String input = JOptionPane.showInputDialog ("Please
enter a String");
String x = new String(input);
String test[] = {x};
for (int k = 0; k < test.length; k++)
System.out.println(test[k]);works. Simple really...thanksThis is completely different from what you previously said you wanted to do. What's the point of putting a String into a one-element String array?
Maybe you are looking for
-
How to control the print pages in se71 form or smartforms
Dear All: I have a issue for control the print pages in se71 form or smartforms. For example:my report used form or smartforms to print.it have 12 total pages.but user want to print the .3rd page.3rd page is customized. How can I
-
BADI for BP open (display or change mode) event
Hi, When a user opens a BP (via BP transaction or open method of BOR object) in CRM, I want to do some custom check. Based on the check, I want to decide whether this user is allowed to open this BP or not. If this check fails, I want to display an e
-
In my photo app it says syncing and importing x of x
Ok so I am running iOS5 beta 6. I don't want to update to beta 7 because I heard it has some problems and I don;t have time to deal with that. Whenever I go to my ohoto app, under the albums, it says "Syncinc and Importing x of x". In my case it says
-
Stolen iPhone Question :(
Hey all, So this is my story. Basically, I was taking a cab home early in the morning on christmas eve and I guess my brand new iPhone 5S fell out of my pocket and I left it in the cab . I realized it was gone the next morning, so I instantly logged
-
I designed num1,num2 and num3 fields.Add and exit push buttons.Add push button makes numbers in num1 and num2 add,display it in num3.It works fine with 'Add' push button.I modified input field such that if num1 number is less than 4,i want num1 displ