Blundell
Blundell

Reputation: 76536

Get a less specific number - from another number

Right, sorry I can't think of the correct words to google this. So I'll have to ask.

I've got a long (System.currentTimeMillis())

Lets say

3453646345345345

I want to remove the last six (or other number of) digits and I think I can do this doing some kind of bit shift?

so I would end up with

3453646345

EDIT

I wanted to get the System.currentTimeMillis() within a time box, so if I ask for the time then ask again 29 seconds later it will return the same number but if I ask 31 seconds later it will return a different number. With the 30 second timebox being configurable.

Upvotes: 2

Views: 122

Answers (3)

InsertMemeNameHere
InsertMemeNameHere

Reputation: 2433

Depending on what you want to do (in base 10, I assume), you can do this:

int64_t radix = 1000000; // or some other power of 10

x -= x%radix; // last 6 decimal digits are now 0
              // e.g: from 3453646345345345 to 3453646345000000

Or this (as in the previous answer):

x /= radix; // last 6 decimal digits are gone, the result rounded down
            // e.g: from 3453646345345345 to 3453646345

Response to Edit

For your purposes, you could change radix in the modulus example to 30000:

int64_t timeInterval = 30000;
displayTime = actualTime - (actualTime % timeInterval);

Where displayTime and actualTime are in milliseonds. displayTime will, in this case, have a (rounded-down) granularity of 30 seconds while remaining a unit of milliseconds.

To have a rounded up granularity, you can do the following:

int64_t timeInterval = 30000;
int64_t modulus = actualTime % timeInterval;
displayTime = actualTime - modulus + (modulus?timeInterval:0);

Though, based on what you are asking, it seems you just want to update a display value only every few ticks. The following will work as well:

if((actualTime - displayTime) >= timeInterval){
    displayTime = actualTime - (actualTime % timeInterval);
}

Pardon the C integer types, I just prefer to be unambiguous about the width of integer I'm using :P.

Upvotes: 1

Keppil
Keppil

Reputation: 46229

To build on @Yob's answer, you can make the number of digits to remove configurable by creating a method like this:

public long removeDigits(long number, int digitsToRemove) {
    return number / (long)Math.pow(10, digitsToRemove);
}

Upvotes: 3

Adam Sznajder
Adam Sznajder

Reputation: 9216

You have to simply divide it by 1M long shorter = System.currentTimeMillis() / 1000000L;

Upvotes: 6

Related Questions