Knowledge Base Nr: 00336 evalstring.java - http://www.swe-kaiser.de

Downloads:

Java: Evaluate Value from String

  
private String EvaluateMacroString(String sText)
{
String sCalcFlaot = sText.replaceAll("CALCFLOAT\\((.*)\\)", "$1");
String sCalc = sText.replaceAll("CALC\\((.*)\\)", "$1");

if (!sCalcFlaot.equals(sText))
{
String sSplit[] = sCalcFlaot.split("[+-/\\*]");
sSplit[0] = sSplit[0].trim();
sSplit[1] = sSplit[1].trim();

try
{
if (sCalc.contains("+"))
sText = Float.toString( Float.parseFloat(sSplit[0]) + Float.parseFloat(sSplit[1]));
else if (sCalc.contains("-"))
sText = Float.toString( Float.parseFloat(sSplit[0]) - Float.parseFloat(sSplit[1]));
else if (sCalc.contains("*"))
sText = Float.toString( Float.parseFloat(sSplit[0]) * Float.parseFloat(sSplit[1]));
else if (sCalc.contains("/"))
sText = Float.toString( Float.parseFloat(sSplit[0]) / Float.parseFloat(sSplit[1]));
}
catch (Exception e)
{
sText = "*NAN*";
}
}
else if (!sCalc.equals(sText))
{
String sSplit[] = sCalc.split("[+-/\\*]");
sSplit[0] = sSplit[0].trim();
sSplit[1] = sSplit[1].trim();

try
{
if (sCalc.contains("+"))
sText = Integer.toString( Integer.parseInt(sSplit[0]) + Integer.parseInt(sSplit[1]));
else if (sCalc.contains("-"))
sText = Integer.toString( Integer.parseInt(sSplit[0]) - Integer.parseInt(sSplit[1]));
else if (sCalc.contains("*"))
sText = Integer.toString( Integer.parseInt(sSplit[0]) * Integer.parseInt(sSplit[1]));
else if (sCalc.contains("/"))
sText = Integer.toString( Integer.parseInt(sSplit[0]) / Integer.parseInt(sSplit[1]));
}
catch (Exception e)
{
sText = "*NAN*";
}
}
else
{
sText = FormatMacroString(sText); //unbekannte funktion - evtl. formatierung
}

return sText;
}