Home > database >  How can I get rid of decimal? (The decimal somehow still take action)
How can I get rid of decimal? (The decimal somehow still take action)

Time:07-25

I'm trying to make a "Distance & Speed to Time" But the decimal is obstruct me to calculate the minute part. Like... the hour part still have decimal value somewhere.

This is what I want

In this example Distance is 130 km and speed is 40 km/hr

Answer I want is

3 Hour(s) 15 Minute(s) 0 Second(s)

But what I get is

3 Hour(s) **0 Minute(s) 0 Second(s)**

float Bx = 130;
float By = 40;
int x = (int) Bx;
int y = (int) By;
var KeepSecond = (x / y * 3600) ;
var HourX = KeepSecond/3600;

int Hour = (int) HourX;
var MinuteX = (KeepSecond-(Hour*3600))/60;
int Minute = (int) MinuteX;
var SecondX = (KeepSecond-(Hour*3600)-(Minute*60));
int Second = (int) SecondX;
String result = String.format(Hour " Hour(s) " Minute " Minute(s) " Second " Second(s) ");
Answer.setText(result);

CodePudding user response:

You're doing an int division on distance/speed : 130/40 gives 3 with int types

You need the double or float division of 130.0/40.0 which gives expected 3.25

var KeepSecond = (Bx / By * 3600);

Also use meaningfull variable name and follow Java convention which is lowerCamelCase for variable (UpperCamelCase for class name)

float distance = 130;
float speed = 40;
var keepSecond = (distance / speed * 3600);

int hourInt = (int) keepSecond / 3600;
int minuteInt = (int) (keepSecond - (hourInt * 3600)) / 60;
int secondInt = (int) (keepSecond - (hourInt * 3600) - (minuteInt * 60));
  • Related