-1

Say i have 2 strings "123,21" and "22,41" i want to subtract both these numbers and return the output in String format itself in Java.

I am unable to identify how can i use Number.format() to do this.

Also how can i convert this string to big decimal?

Gaurav Setia
  • 69
  • 2
  • 8
  • 2
    You need to parse the number with [a locale that supports comma as the decimal separator](https://docs.oracle.com/cd/E19455-01/806-0169/overview-9/index.html) – BackSlash Nov 23 '18 at 10:40

4 Answers4

1

First, you can follow this way to use Number.format().

Then, you can simply create BigDecimal with the double result.

After various exchange via comments, this is my final answer, allowing to control decimal separator, and grouping separator:

public static final BigDecimal convertToBigDecimal(String stringNumber1, String stringNumber2, char separator, char groupingSeparator)
            throws ParseException {
        Locale myLocale = Locale.FRANCE;
        DecimalFormatSymbols decimalSeparator = new DecimalFormatSymbols(myLocale);
        decimalSeparator.setDecimalSeparator(separator);
        decimalSeparator.setGroupingSeparator(groupingSeparator);
        DecimalFormat format = (DecimalFormat) DecimalFormat.getInstance(myLocale);
        format.setDecimalFormatSymbols(decimalSeparator);

        Number number1 = format.parse(stringNumber1.trim());
        Number number2 = format.parse(stringNumber2.trim());
        double substractResult = number1.doubleValue() - number2.doubleValue();

        // If you want back a String presentation => String stringFormat = "" +
        // substractResult;

        return new BigDecimal(substractResult);
    }

This way you fully control locale and decimal separator as you wish.

If you want to use coma as default decimal separator, you can add this overload:

public final BigDecimal convertToBigDecimal(String stringNumber1, String stringNumber2)
            throws ParseException {
        return convertToBigDecimal(stringNumber1, stringNumber2, ',', '.');
    }

    public final BigDecimal convertToBigDecimal(String stringNumber1, String stringNumber2, char separator)
            throws ParseException {
        return convertToBigDecimal(stringNumber1, stringNumber2, separator, '.');
    }

You can then easily use this new function

System.out.println(convertToBigDecimal("123,21", "22,41", ','));
System.out.println(convertToBigDecimal("123.21", "22.41", '.'));
System.out.println(convertToBigDecimal("123,441.33", "122,441.22", '.', ','));
System.out.println(convertToBigDecimal("59.998,50", "698,43", ',', '.'));
System.out.println(convertToBigDecimal("59.998,50", "49.998,50", ','));
Bsquare ℬℬ
  • 4,423
  • 11
  • 24
  • 44
  • Hi, does it solve your issue? – Bsquare ℬℬ Nov 25 '18 at 00:17
  • Hey @Bsquare thanks for the help! Everything works good except i get this exception: java.text.ParseException: Unparseable number: " 1 " – Gaurav Setia Nov 26 '18 at 09:14
  • 1
    See, you have an heading, and trailing space characters at the beginning of " 1 "; you should use trim() method on String, before trying to parse them. – Bsquare ℬℬ Nov 26 '18 at 10:17
  • i guess there is still something missing! for the above code in locale Locale.FRANCE while trying to subtract 59.998,5 and 1.399,99 i get output as 58. basically it removes everything after "." and does a 59-1=58 So basically the problem still persists! – Gaurav Setia Nov 27 '18 at 10:30
  • You should use DecimalFormat instead of Number Format, and define the wanted symbol to be Culture indépendant. I'll update my answer as soon as I m back on my computer – Bsquare ℬℬ Nov 27 '18 at 11:11
  • Cool! I am playing around with DecimalFormat, but i am yet unable to find a generic fix which handles all use cases like: 1. 123,441.33 - 122,441.22 = 1000.11 2. 59.998,50 - 698,43 = 599260.07 3. 59.998,50 - 49.998,50 = 10000 – Gaurav Setia Nov 27 '18 at 11:56
  • 1
    Done ... I wrote you an utility method allowing you to control everything, and matching all situation ;) – Bsquare ℬℬ Nov 27 '18 at 13:53
  • I updated with grouping separator management. Does it solve your issue? – Bsquare ℬℬ Nov 27 '18 at 16:03
  • looks amazing :) – Gaurav Setia Nov 28 '18 at 11:42
0

I think decimal format with this custom formatting can be provided to convert the text to an integer or double as per requirement.

 public static void main(String[] args) throws ParseException {                                            
     String text1 = "123,21";                                                                              
     String text2 = "22,41";                                                                               
     NumberFormat nf_in = new DecimalFormat("###,##");                                                     
     int number1 = nf_in.parse(text1).intValue();                                                          

     System.out.println("Number 1 "+number1);                                                              

     int number2 = nf_in.parse(text2).intValue();                                                          

     System.out.println("Number2 "+number2);                                                               

     System.out.println("Subtract Number2 from number 1"+ (number1-number2));                              
 }                                                                                                         
unnik
  • 1,123
  • 5
  • 18
  • 37
0
public static void main(String[] args) throws ParseException {
        String text1 = "123,21";
        String text2 = "22,41";


        DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols();
        decimalFormatSymbols.setDecimalSeparator(',');
        NumberFormat nf_in = new DecimalFormat("##,##",decimalFormatSymbols);

        double number1 = nf_in.parse(text1).doubleValue();

        System.out.println("Number 1 "+number1*1);

        double number2 = nf_in.parse(text2).doubleValue();

        System.out.println("Number2 "+number2*1);

        double outputvalue = number1 - number2;


        System.out.println( outputvalue);
    }

I think using DecimalFormatSymbols with Decimal format should do allow you to use comma as the decimal symbol.

Refer Best way to parseDouble with comma as decimal separator?

unnik
  • 1,123
  • 5
  • 18
  • 37
-1

You maybe want to values next to comma and subtract them. A common and a handy way I know is using split() method that will return an array of strings.

String text = "123,21";
String[] values = text.split(","); //this will add all the strings before or after a ",".
String answer = (Integer.parseInt(values[0])-Integer.parseInt(values[1])).toString();
System.out.println("Answer: "+answer); //will output 102
Seniru Pasan
  • 753
  • 1
  • 7
  • 13
  • 1
    But OP wants to subtract `123,21` and `22,41` as decimals. The question is not about doing `123 - 21`. – BackSlash Nov 23 '18 at 11:35