Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

android - Getting a percent in kotlin

I have followed a few other similar posts on here but despite following some tips I am still not getting the result I expect

I have two variables: TimeTaken and TimeGiven. Both are stored as Int values (representing seconds)

When I output the individual values they come out correctly as integers

Example

TimeTaken = 4 and TimeGiven = 10

I then have a function to get a percent as an integer from the value. I have seen different ways and here are two of them:

Option 1

private fun getPercent(timeTaken:Int,timeGiven:Int): Int {

    return ((timeTaken.toDouble() / timeGiven)*100).roundToInt()

}

Option 2

private fun getPercent(timeTaken:Int,timeGiven:Int): Int {

    return (timeTaken / timeGiven)*100

}

When I am calling this e.g.

getPercent(TimeTaken,TimeGiven)

I always get 0 as a return when I output the result to a textview

To see the value in my textview (until I can prove it working) I am simply doing this(where TIMETAKitm.text has already been initialised as a view);

TIMETAKitem.text = getPercent(TimeTaken,TimeGiven).toString()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this code

return ((timeTaken.toDouble() / timeGiven)*100).toInt()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...