-6

Good Morning,

I have a String = "1481807989.1524"

I need to add + 1 to this string

Example 1:

String = "1481807989.1524"

New String = "1481807989.1525"

Example 2:

String = "1481807989.1999"

New String = "1481807989.2000"

I tried to do it this way but it did not answer:

String str;

Str = str.charAt (str.length () - 1);
  • 5
    You have to change the number to float, do the math you want, and then turn back into String. – k_kaz Dec 15 '16 at 13:56
  • 3
    Is it one decimal number and do you want to add 0.001; or are there two numbers, separated by '.'? – C. L. Dec 15 '16 at 13:57
  • 3
    http://stackoverflow.com/questions/5769669/convert-string-to-double-in-java, then add, then http://stackoverflow.com/questions/5766318/converting-double-to-string – Tom Dec 15 '16 at 13:57
  • What you gotta do, I know. But how to do in java (Code) I am in difficulties could help me? – Rafael Calino Dec 15 '16 at 13:58
  • 2
    @RafaelCalino look at what Tom just linked. People are not here to do your homework for you. – KyleKW Dec 15 '16 at 14:01

1 Answers1

5

Parse the value as a whole and then add the value you desire.

new BigDecimal(/* your string */).add(BigDecimal.ONE)

Or if I read your code correctly, you always want to add new BigDecimal("0.001").

EDIT: if you really want to just change the last digit, use something like the following:

public BigDecimal incrementLastDigit(String value) {
    BigDecimal decimal = new BigDecimal(value);
    return new BigDecimal(decimal.unscaledValue().add(BigInteger.ONE), decimal.scale());
}

Samples:

incrementLastDigit("1234.1234"); // gets you 1234.1235
incrementLastDigit("1234.1"); // gets you 1234.2
incrementLastDigit("9999999999999999999999999999999999.99999999999999999999999999999"); 
// gets you 10000000000000000000000000000000000.00000000000000000000000000000
Roland
  • 22,259
  • 4
  • 57
  • 84
  • the string could be `123`, `123.1` , '123.123`, '8999999999999999999999999999.999999999999999999999999`. anyway, hard coded `0.001` looks not nice. – Kent Dec 15 '16 at 13:59
  • Agreed. This should rather lead in the right direction. The pattern I saw, was that `0.0001` was added ;-) And regarding the input strings. Don't forget, that "nonsense" is a valid input string too ;-) Sanity checks were not asked ;-) – Roland Dec 15 '16 at 14:13
  • I did the function but look at the result: VAR: 1481811454.1579 VAR NEW: 1481811455.1579 He has to change in 1579. – Rafael Calino Dec 15 '16 at 14:22