John dahat
John dahat

Reputation: 127

Make to not show numbers after decimal

Input :

double a = 21.66468                     
double b = 21.86494

String output_a = Sting.format("%.0f",a);
String output_b = Sting.format("%.0f",b);

Output :

output_a = 22              
output_b = 22

But i want output :

output_a = 21                 
output_b = 21

Here the problem is it's increasing the number by 1 automatically

Upvotes: 0

Views: 82

Answers (4)

Robert Downey
Robert Downey

Reputation: 21

Here i will demonstrate you that how to make your decimal number short. Here i am going to make it short upto 4 value after decimal.

double value = 12.3457652133 value =Double.parseDouble(new DecimalFormat(

Upvotes: 1

Marvin
Marvin

Reputation: 14255

The underlying Formatter says that "the value will be rounded using the round half up algorithm" and it apparently does not offer direct options to prevent that.

What you seem to want is not rounding but truncating and a simple way of doing that is casting to int:

jshell> double a = 21.66468;
a ==> 21.66468

jshell> System.out.println((int) a);
21

Or to get the String:

jshell> double a = 21.66468;
a ==> 21.66468

jshell> String output_a = Integer.toString((int) a);
output_a ==> "21"

Upvotes: 1

Norbert
Norbert

Reputation: 254

Simply cast to int

System.out.println("double a: " + (int)a); System.out.println("double b: " + (int)b);

Upvotes: 2

Piper2
Piper2

Reputation: 299

In such a case you will want to utilize the Math.floor() java method...

something like this

double a = 21.66468                     
double b = 21.86494

// This trancates you doubles and later casts them into integers
int aWithNoDecimals = (int) Math.floor(a);
int bWithNoDecimals = (int) Math.floor(a);


/* 
   You do not want to use Strings here... 
   You can just output the ints and you are good
*/

//String output_a = Sting.format("%.0f",a);
//String output_b= Sting.format("%.0f",b);

// Something like this
int output_a = aWithNoDecimals;
int output_b = bWithNoDecimals;

Upvotes: 1

Related Questions