June 09, 2012

Reg: Return round value from given string with decimal format

import java.text.DecimalFormat;

public class RoundValueFromGivenStringDecimalFmt {

private static String roundValue(String str) {
System.out.println("[Given String Value]: " + str);
float a = (Float.valueOf(str)).floatValue();
System.out.println("[Original String Value]: " + a);
a = (float) (a + 0.01f);
DecimalFormat df = new DecimalFormat();
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(2);
System.out.println("[Round String Value]: " + df.format(a));
str = df.format(a);
return str;
}

public static void main(String[] args) {
String sValue = "12123.9";
roundValue(sValue);
}
}
//Output:
//Scenario 1:
//[Given String Value]: 12123.11111
//[Original String Value]: 12123.111
//[Round String Value]: 12,123.12


//Scenario 2:
//[Given String Value]: 12123.13455
//[Original String Value]: 12123.135
//[Round String Value]: 12,123.14

//Scenario 3:
//[Given String Value]: 12123.18444
//[Original String Value]: 12123.185
//[Round String Value]: 12,123.19

//Scenario 4:
//[Given String Value]: 12123
//[Original String Value]: 12123.0
//[Round String Value]: 12,123.01

//Scenario 5:
//[Given String Value]: 12123.9
//[Original String Value]: 12123.9
//[Round String Value]: 12,123.91

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