June 09, 2012

Req: Return round value from given string with string format

import java.text.DecimalFormat;

public class RoundValueFromGivenStringWithStringFmt {
public static void main(String[] args) {
String ss = "144333.9566666";
roundValueStr(ss);
}

private static String roundValueStr(String str) {
System.out.println("[Given String Value]: " + str);
double dValue = Double.valueOf(str);
int rValue = (int) Math.round(dValue * 100);
double fValue = rValue / 100.0;
String sValue = String.valueOf(fValue);
System.out.println("[Round String Value]: " + sValue);
return sValue;
}
}

//Output:
//Scenario 1:
//[Given String Value]: 144333.1234
//[Round String Value]: 144333.12

//Scenario 2:
//[Given String Value]: 144333.8888
//[Round String Value]: 144333.89

//Scenario 3:
//[Given String Value]: 144333.89999
//[Round String Value]: 144333.9

//Scenario 4:
//[Given String Value]: 144333.91111
//[Round String Value]: 144333.91

//Scenario 5:
//[Given String Value]: 144333.9566666
//[Round String Value]: 144333.96

No comments:

Post a Comment

I'm certainly not an expert, but I'll try my hardest to explain what I do know and research what I don't know.

My Favorite Site's List

#update below script more than 500 posts