0

I have a string like 46542.5435657468, but i want format this string and need only two charector after dot "." like 46542.54. Please suggest me which String method i need to use.

mvts himm
  • 117
  • 1
  • 4
  • 16
  • possible duplicate of [Round a double to 2 significant figures after decimal point](http://stackoverflow.com/questions/2808535/round-a-double-to-2-significant-figures-after-decimal-point) – Pankaj Kumar Sep 12 '13 at 12:22

5 Answers5

6
String.format("%.2f", Double.valueOf("46542.5435657468"));
Danny
  • 7,368
  • 8
  • 46
  • 70
3

maybe String.format()?

String.format("%.2f", floatValue);
Nachi
  • 4,218
  • 2
  • 37
  • 58
3

You can use DecimalFormat

first declare this at the top

DecimalFormat dtime = new DecimalFormat("#.##"); //change .## for whatever numbers after decimal you may like.

then use it like this

dtime.format(your string);

like:

 String a = "46542.5435657468";
dtime.format(a);

output will be 46542.54

Ahmed Ekri
  • 4,601
  • 3
  • 23
  • 42
1

You can use a method like this.

private static String extract(String text) {
    String[] values = text.split(".");
    return values[0] + "." + values[1].substring(0, 2);
}
Yuichi Araki
  • 3,438
  • 1
  • 19
  • 24
0

The method indexOf tell you the position of the character "." ok?

The method substring cut a peace of the string from the begining (value 0) until the positio of the character "." plus 2 digits more.

public String getNumberFormated(String  yourNumber)
{
   return  yourNumber.substring(0, yourNumber.indexOf(".") + 2);
}

Do you like my solution?

Juan Pedro Martinez
  • 1,924
  • 1
  • 15
  • 24