Print rounded digits without extra zeros - java

I'm trying to round using BigDecimal.ROUND_HALF_UP but am not getting expected results. This code:
String desVal="21.999";
BigDecimal decTest=new BigDecimal(
String.valueOf(desVal)
)
.setScale(
Integer.parseInt(decimalPlaces), BigDecimal.ROUND_DOWN
);
System.out.println(decTest);
Gives the following results:
decimalPlaces=1 it is displaying 21.9 //correct
decimalPlaces=2 displaying 21.99 //correct
decimalplaces=3 displaying 21.999 //correct
decimalplaces=4 displaying 21.9990 //incorrect
I want to get the following:
decimalPlaces=1 should display 21.9
decimalPlaces=2 should display 21.99
decimalplaces=3 should display 21.999
decimalplaces=4 should display 21.999
Is there a way to do this with standard Java (ie no external libraries)?

Use BigDecimal#stripTrailingZeros():
String[] decimalPlaces = new String[] {"2", "2", "3", "4", "4"};
String[] desVal = new String[] {"20", "21.9", "21.90", "21.99999", "21.99990"};
for (int i = 0; i < desVal.length; i++) {
BigDecimal decTest = new BigDecimal(desVal[i]);
if (decTest.scale() > 0 && !desVal[i].endsWith("0") && !(Integer.parseInt(decimalPlaces[i]) > decTest.scale())) {
decTest = decTest.setScale(Integer.parseInt(decimalPlaces[i]),
BigDecimal.ROUND_DOWN).stripTrailingZeros();
}
System.out.println(decTest);
}
Output:
20
21.9
21.90
21.9999
21.99990

int decPlaces = Math.min(Integer.parseInt(decimalPlaces),
desVal.length() - desVal.indexOf(".") + 1);
BigDecimal decTest=
new BigDecimal(String.valueOf(desVal)).
setScale(decPlaces, BigDecimal.ROUND_DOWN);

You can use java.text.NumberFormat
NumberFormat nf = NumberFormat.getInstance();
System.out.println(nf.format(decTest));
If you want to preserve original scale, then
String desVal="21.99901";
BigDecimal decTest=new BigDecimal(String.valueOf(desVal));
int origScale = decTest.scale();
decTest = decTest.setScale(4, BigDecimal.ROUND_DOWN);
System.out.println(String.format("%."+origScale+"f", decTest));

If you want to print trailing zeroes, but not all of them, you will need a DecimalFormat.
The trick is that in your case, you need to build the Format String depending on the number of decimals in the original input String.
int decimalPlaces = 10;
String desVal="21.99900";
// find the decimal part of the input (if there is any)
String decimalPart = desVal.contains(".")?desVal.split(Pattern.quote("."))[1]:"";
// build our format string, with the expected number of digits after the point
StringBuilder format = new StringBuilder("#");
if (decimalPlaces>0) format.append(".");
for(int i=0; i<decimalPlaces; i++){
// if we've passed the original decimal part, we don't want trailing zeroes
format.append(i>=decimalPart.length()?"#":"0");
}
// do the rounding
BigDecimal decTest=new BigDecimal(
String.valueOf(desVal)
)
.setScale(
decimalPlaces, BigDecimal.ROUND_DOWN
);
NumberFormat nf = new DecimalFormat(format.toString());
System.out.println(nf.format(decTest));

Related

How can i make a Number Format Like 000"+"000 in android

I want to make a number format like 000"+"000. The rule will be 3 digits "+" 3 digits. I will give you some examples below.
I have tried some codes before i will show them below. I think i have to use NumberFormat class. My codes are below. by the way my number maximum have 6 digits if number has less digits the missing digits(which will be in left), has to be 0.
I tried
NumberFormat numberFormat = new DecimalFormat("000'+'000");
but it gave error which is
Unquoted special character '0' in pattern "000'+'000"
but it was worked when i make
NumberFormat numberFormat = new DecimalFormat("'+'000");
or
NumberFormat numberFormat = new DecimalFormat("000'+'");
So simply i can make number-plus or plus-number but i can't make number(3 digit)-plus-number(3 digit)
I expect to get these outputs for these inputs:
input: 4032
output: 004+032
input : 5
output: 000+005
input: 123450
output: 123+450
input: 10450
output: 010+450
With a trick: change the grouping separator symbol to +:
DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.getDefault());
symbols.setGroupingSeparator('+');
NumberFormat nf = new DecimalFormat("000,000", symbols);
int x = 3250;
System.out.println(nf.format(x));
Result:
003+250
Or use a method like this:
public static String specialFormat(int number) {
NumberFormat nf = new DecimalFormat("000");
return nf.format(number / 1000) + "+" + nf.format(number % 1000);
}
it formats separately the 3 first digits and the 3 last digits and concatenates with a + in the middle.
Use it:
int x = 5023;
System.out.println(specialFormat(x));
Result:
005+023
What you want is not a decimal syntax. Therefor, you cannot use the DecimalFormat, because it handles all kinds of localized numbers but not arbitrary ones like yours. However, you might want to implement your own java.text.Format.
What about using this kind of method and later convert it to the format you want
generateNumbers(String val) {
int len = val.length();
String finalValue;
StringBuffer sb = new StringBuffer();
if (len < 6) {
for (int i = 6; i > len; i--) {
sb.append("0");
}
finalValue = sb.append(val).toString();
} else {
finalValue = val;
}
System.out.println(finalValue.substring(0, 3) + "+" + finalValue.substring(3));
}
for testing you can call this
generateNumbers("4032");
generateNumbers("5");
generateNumbers("123450");
generateNumbers("10450");
Output is
004+032
000+005
123+450
010+450
Let me know if it's useful.

java: get different parts of NumberFormat.getCurrencyInstance() result

In Java, with NumberFormat.getCurrencyInstance(), I can get a formatted string representing a price. e.g.
NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.GERMANY);
System.out.println(nf.format(20.10)); // "20,10 €"
Is there an easy way to get the different part of this formatted string? i.e. something like
integerPart -> 20
decimalPart -> 10
currencySymbol -> €
decimalSeparator -> ,
Thanks!
You're really asking for two separate things:
integerPart and decimalPart belong to the input value. They can be calculated with some simple math:
double input = 20.10;
int integerPart = (int)input; // 20
int decimalPart = (int)((input - integerPart) * 100); // 10
currencySymbol and decimalSeparator relate to the output value. They can be retrieved using the DecimalFormatSymbols class:
DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(Locale.GERMANY);
String currencySymbol = symbols.getCurrencySymbol(); // €
char decimalSeparator = symbols.getDecimalSeparator(); // ,

cast String with period and comma to int

how to cast String with period and comma to int, like
String a "9.000,00"
int b = Integer.parseInt(a);
when I run this code, I get an error message : Exception in thread "main" java.lang.NumberFormatException: For input string: "9.000,00"
If you want to get as result 900000 then simply remove all , and . and parse it with for instance with Integer.parseInt or Long.parseLong or maybe even better use BigInteger if number can be large.
String a = "9.000,00";
BigInteger bn = new BigInteger(a.replaceAll("[.,]", ""));
System.out.println(bn);
Output: 900000
But if you want to parse 9.000,00 into 9000 (where ,00 part is decimal fraction) then you can use NumberFormat with Locale.GERMANY which uses form similar to your input: 123.456,78
String a = "9.000,00";
NumberFormat format = NumberFormat.getInstance(Locale.GERMANY);
Number number = format.parse(a);
double value = number.doubleValue();
//or if you want int
int intValue = number.intValue();
System.out.println(value);
System.out.println(intValue);
Output:
9000.0
9000
final String a = "9.000,00";
final NumberFormat format = NumberFormat.getInstance(Locale.GERMAN); // Use German locale for number formats
final Number number = format.parse(a); // Parse the number
int i = number.intValue(); // Get the integer value
Reference
To do that, you need to use java.text.NumberFormat and NumberFormat.getInstance(Locale.FRANCE) (or another compatible Locale)
import java.text.NumberFormat;
import java.util.Locale;
class Test {
public static void main(String[] args) throws Exception {
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
String a = "9.000,00";
a = a.replaceAll("\\.", "");
Number number = format.parse(a);
double d = number.doubleValue();
int c = (int) Math.floor(d);
System.out.println(c);
}
}
prints 9000 as you want ( and now is an int ) !
If I print every intermediate step :
import java.text.NumberFormat;
import java.util.*;
class test {
public static void main(String[] args) throws Exception {
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
String a = "9.000,00";
a = a.replaceAll("\\.", "");
System.out.println(a); // prints 9000,00
Number number = format.parse(a);
System.out.println(number); // prints 9000
double d = number.doubleValue();
System.out.println(d); // prints 9000.0
int c = (int) Math.floor(d);
System.out.println(c); // prints 9000
}
}
so if Okem you want 9000,00 as you're saying in your comment, you just need
a = a.replaceAll("\\.", "");
System.out.println(a);
which gives you an output of 9000,00
I hope that helps.
Try this -
String a = "9.000,00";
a = a.replace(",","");
a = a.replace(".","");
int b = Integer.parseInt(a);
I think DecimalFormat.parse is the Java 7 API way to go:
String a = "9.000,00";
DecimalFormat foo = new DecimalFormat();
Number bar = foo.parse(a, new ParsePosition(0));
After that, you go and be happy with the Number you just got.
If you want the answer to be 900000 (it doesn't make sense to me, but I'm replying to your question) and put that into an int go with:
int b = Integer.parseInt(a.replaceAll(",","").replaceAll("\\.",""));
as already outlined in the comments.

Set Scale for Decimals stored in a String Array in an Object

I have a string array in an object which is storing a decimal value.
String [] array = "12345.123456789";
I want it to be formatted as 12345.1234
I tried it with the following but resulted in a Number Format Exception.
BigDecimal value = new BigDecimal(array.toString()).setScale( 4, BigDecimal.ROUND_HALF_UP );
array = ( Object )value.toString();
I am new to java so can anyone please help...
String [] array = "12345.123456789"; is not a valid statement - either it is a String or an array, so you need to choose between the following two statements:
String s = "12345.123456789"; //a string
String[] array = {"12345.123456789"}; //an array
If you use the first form, you can round it with:
BigDecimal rounded = new BigDecimal(s).setScale( 4, BigDecimal.ROUND_HALF_UP );
String roundedStr = rounded.toString();
If you use the second form, you can use this:
BigDecimal rounded = new BigDecimal(array[0]).setScale( 4, BigDecimal.ROUND_HALF_UP );
String roundedStr = rounded.toString();
String [] array = {"12345.123456789"};
StringBuilder numbers = new StringBuilder();
for(int i=0;i<array.length;i++)
{
BigDecimal digits = new BigDecimal(array[i]).setScale( 4, BigDecimal.ROUND_HALF_UP );
numbers.append(digits.toString());
}
System.out.println(numbers);

Double number's multiplication with out precision and commas

i have an array, a double array like...
Double my_array = new Double[] {6272640.0, 43560.0, 4840.0, 0.0015625, 4046856422.400000095, 40468564.223999999, 4046.856422400, 0.004046856, 1.0, 0.404685642};
and in my program i want to multiply each of that elements with some integer values...
which i accept through a variable n.
i had done it in my program as...
for(int 1=0;i<my_array.length;i++)
{
my_array[i] = n*my_array[i];
}
when i try to print the result, i gets value as exponentials...
like, 3.23E etc etc......
I need the result as double value up to 8 decimal points...
What should i do to get it
You should format your output.
http://docs.oracle.com/javase/tutorial/java/data/numberformat.html (general explanation)
http://download.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html (formatting symbols)
double yourDouble = 0.1234567890;
DecimalFormat myFormatter = new DecimalFormat("0.00000000");
System.out.println(myFormatter.format(yourDouble));
Should print "0.12345678".
try this way
java.text.DecimalFormat df = new java.text.DecimalFormat("###.########"); // define here how much you want precision
for(int i=0;i<my_array.length;i++)
System.out.println(df.format(my_array[i]));
Does
String str = String.valueOf(double d);
solve the problem?
Try this out:
double value = X.XX;
DecimalFormat decimalFormat = new DecimalFormat();
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator('.'); // if needed
symbols.setGroupingSeparator('\u0020'); // if needed
decimalFormat.setDecimalFormatSymbols(symbols);
decimalFormat.setMaximumFractionDigits(8); // or any other
decimalFormat.setMinimumFractionDigits(8); // or any other
decimalFormat.setRoundingMode(RoundingMode.HALF_EVEN); // if needed
return decimalFormat.format(value);
Check this site...
http://www.jguru.com/faq/view.jsp?EID=1307290
I had changed my double array to String array, like
String my_array[];
my_array = new String[] {"1.006944444","6.45160645160", "0.00000326701", "0.0076001595"};
// then used my for loop like
BigDecimal b1 = new BigDecimal(n);
for(int 1=0;i<my_array.length;i++)
{
BigDecimal b2 = new BigDecimal(Double.parseDouble(my_array[i]));
BigDecimal result = b1.multiply(b2);
System.out.println(result.doubleValue);
}
just check it yourself. as i had just described the logic, my for loop had much more to do..

Categories