Skip to content

Instantly share code, notes, and snippets.

@pedrex1987
Last active April 23, 2020 15:59
Show Gist options
  • Save pedrex1987/2aba5f3c334c57b9a31def37d2e860f9 to your computer and use it in GitHub Desktop.
Save pedrex1987/2aba5f3c334c57b9a31def37d2e860f9 to your computer and use it in GitHub Desktop.
Extensions
fun Int.toMoney(): String {
return java.text.NumberFormat.getCurrencyInstance(java.util.Locale("pt", "BR"))
.apply {
maximumFractionDigits = 2
minimumFractionDigits = 2
}.format(this / 100.0)
}
fun Double.toCents(): Int = (java.math.BigDecimal(this)
.setScale(2, java.math.RoundingMode.HALF_UP)
.multiply(java.math.BigDecimal(100))
.toInt())
fun loadImage(urlImage: String?, imageView: ImageView) {
if (urlImage == null) {
imageView.setImageDrawable(
ContextCompat.getDrawable(
imageView.context,
R.drawable.placeholder
)
)
} else {
Glide
.with(imageView.context)
.load(urlImage)
.apply(
RequestOptions().apply {
diskCacheStrategy(DiskCacheStrategy.ALL)
priority(Priority.HIGH)
placeholder(R.drawable.placeholder)
error(R.drawable.placeholder)
dontTransform()
dontAnimate()
fitCenter()
}
)
.into(imageView)
}
}
fun String.getOnlyNumbers(): String {
return replace("[^0-9]".toRegex(), "")
}
fun String?.phoneFormat(): String {
if (this == null) {
return ""
}
var text = this
val formattedString = StringBuilder()
val endIndex = 11
text = text.getOnlyNumbers()
var allDigitString: String = text
var totalDigitCount = allDigitString.length
if (totalDigitCount > endIndex) {
allDigitString = allDigitString.substring(0, endIndex)
totalDigitCount--
}
val isLonger = totalDigitCount == endIndex
val dashAfter = if (isLonger) 5 else 4
if (totalDigitCount == 0 || totalDigitCount > 11 && !allDigitString.startsWith("(")
|| totalDigitCount > 12
) {
text.append(allDigitString)
return allDigitString
}
var alreadyPlacedDigitCount = 0
if (totalDigitCount - alreadyPlacedDigitCount > 2) {
formattedString.append(
"("
+ allDigitString.substring(
alreadyPlacedDigitCount,
alreadyPlacedDigitCount + 2
) + ") "
)
alreadyPlacedDigitCount += 2
}
if (totalDigitCount - alreadyPlacedDigitCount > dashAfter) {
formattedString.append(
allDigitString.substring(
alreadyPlacedDigitCount, alreadyPlacedDigitCount + dashAfter
)
+ "-"
)
alreadyPlacedDigitCount += dashAfter
}
if (totalDigitCount > alreadyPlacedDigitCount) {
formattedString.append(
allDigitString
.substring(alreadyPlacedDigitCount)
)
}
text.append(formattedString.toString())
return formattedString.toString()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment