Home > Enterprise >  How can I get the first 5 numbers of a double
How can I get the first 5 numbers of a double

Time:04-08

how can i only have the first 5 numbers in a double?

12345.6789 --> 12345
1.23456789 --> 1.2345
0.123456789 --> 0.1234

I have tried different things such as multiplying the number by the power of 10 and x but x seems to only affect the decimal places, setting it to x decimal places

CodePudding user response:

Using BigDecimal:

  • move the decimal point to the right/left until only the desired number of (significant) digits are in front of the decimal point;
  • set the scale to zero, that is, removed all digits after the decimal point or extend the precision up to the point (if missing digits);
  • move the decimal point back to where it was, undoing first step.
static BigDecimal convert(BigDecimal number, int significant) {
    var beforeDecimal = number.precision() - number.scale();
    var movePoint = significant - beforeDecimal;
    return number
           .movePointRight(movePoint)
           .setScale(0, RoundingMode.DOWN)
           .movePointLeft(movePoint);
}

called like
convert(BigDecimal.valueOf(1.23456789), 5)
or
convert(new BigDecimal("1.23456789"), 5)

to return the BigDecimal:
1.2345

CodePudding user response:

Here is one way.

  • convert to a string.
  • check for a decimal.
  • if not present (= -1) or >= 5, set i to 5. Else set to 6
  • then get the substring from 0 to i.
double[] v = {12345.6789,
1.23456789,
0.123456789};

for (double d : v) {
    String s = Double.toString(d);
    int i = s.indexOf('.');
    i = i < 0 || i >= 5 ? 5 : 6;
    System.out.println(s.substring(0,i));
}

prints

12345
1.2345
0.1234

CodePudding user response:

As others commented, one way to do this is with string manipulation. May not seem elegant, but it gets the job done.

Define some inputs.

double[] doubles = { 12345.6789 , 1.23456789 , 0.123456789 } ;

Loop those inputs. For each one, generate a string. If a FULL STOP is found, take first six characters. If not, five. If the FULL STOP lands in the last place, such as in our first example input, delete.

for( double d : doubles )
{
    String s = String.valueOf( d ) ; 
    String s5 = s.substring( 0 , s.contains( "." ) ? 6 : 5 ) ;
    if( s5.endsWith( "." ) ) { s5 = s5.substring( 0 , s5.length() - 1 ) ; }  // Drop FULL STOP in last place.
    System.out.println( s5 ) ;
}

See this code run live at IdeOne.com.

12345
1.2345
0.1234

Caveat: You may need to internationalize by accounting for a COMMA (,) as the decimal separator rather than a FULL STOP (.) character.

String s5 = s.substring( 0 , ( s.contains( "." ) || s.contains( "," ) ) ? 6 : 5 ) ;
  • Related