0

is java have method to trimming text/string? like this one :
int comaNumber = input.nextInt();
string number = "234,56789";
int coma = number.indexOf(",");
string number = number.substring(0,coma(comaNumber+1));

note : it will search coma character and then it will trim the number based on amount of coma in comaNumber, the result is 234,56 (works)

is any method in java to trimming decimal number to simplify my works? (not trim() function)

Edit: the number of decimal place is specified by user input.

Ardi Renaldi
  • 49
  • 1
  • 5
  • Converse String to Number, format the number using this answer: http://stackoverflow.com/questions/8819842/best-way-to-format-a-double-value-to-2-decimal-places – T D Nguyen Feb 26 '16 at 04:42
  • 1
    You could replace the comma with a period, then use DecimalFormat, or truncate the decimal number to two decimal places and replace the period with a comma again – OneCricketeer Feb 26 '16 at 04:47

3 Answers3

1

The easiest way is to use DecimalFormat. Although, to get that working with a comma you will need to modify the FormatSymbols.

It would be something like this:

    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
    symbols.setDecimalSeparator(',');//this tels DecimalFormat to use ',' as the decimal separator
    String pattern = "#.00";//this means that you want only 2 decimals
    DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
    System.out.println(decimalFormat.parse("221012,28").doubleValue());
    System.out.println(decimalFormat.format(1234.123121));

That prints

221012.28
1234,12
ejoncas
  • 329
  • 2
  • 13
0

You could try using String.format. First switch the comma with a period. For example,

number = number.replace(",",".");
double y = Double.parseDouble(number);
String x = String.format("%.2d",number);
x = x.replace(".",",");

First, you replace the comma with a period. Then you use the parseDouble method(documentation https://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#parseDouble(java.lang.String)). Then you use String.format to save it with only two places after the decimal point. Then change decimal back to comma.

Hope this helps!

FlamingPickle
  • 199
  • 1
  • 3
  • 14
-1

As far as I know, there is no such method. My advice is to create your own method, and then reference it whenever you need it.

Ethan JC Rubik
  • 174
  • 1
  • 1
  • 12