Oleg Gordiichuk
Oleg Gordiichuk

Reputation: 15512

Take value from float number after dot

How correctly extract second valued after coma in Float value.

Example:

var value = 5.435

And I would like to take value second value after coma, that is 3.

How to do this properly?

Upvotes: 0

Views: 2134

Answers (4)

Knight0fDragon
Knight0fDragon

Reputation: 16837

Mod is an expensive operation, instead do

(Int(value * 100)) - (Int(value * 10) * 10)

In your scenario we get

(Int(5.435 * 100)) - (Int(5.435 * 10) * 10);
(Int(543.5)) - (Int(54.35) * 10);
(543) - (54 * 10);
(543) - (540);
3

Upvotes: 1

kostek
kostek

Reputation: 801

In case you want to handle both positive and negative values:

(Int)( abs(value) * 100 ) % 10

If you want to keep the sign, just remove abs

Upvotes: 3

Hutch
Hutch

Reputation: 854

If its always going to be the third decimal, I would do it like this.

var value = 5.435
value *= 100

var digit = value % 10

Upvotes: 1

i486
i486

Reputation: 6573

Maybe this: (int)( value * 100 ) % 10.

Upvotes: 1

Related Questions