1 /* 2 * Copyright 2020 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package androidx.compose.ui.geometry 18 19 import kotlin.math.max 20 import kotlin.math.pow 21 22 // File of internal utility methods used for the geometry library toStringAsFixednull23internal fun Float.toStringAsFixed(digits: Int): String { 24 if (isNaN()) return "NaN" 25 if (isInfinite()) return if (this < 0f) "-Infinity" else "Infinity" 26 27 val clampedDigits: Int = max(digits, 0) // Accept positive numbers and 0 only 28 val pow = 10f.pow(clampedDigits) 29 val shifted = this * pow // shift the given value by the corresponding power of 10 30 val decimal = shifted - shifted.toInt() // obtain the decimal of the shifted value 31 // Manually round up if the decimal value is greater than or equal to 0.5f. 32 // because kotlin.math.round(0.5f) rounds down 33 val roundedShifted = 34 if (decimal >= 0.5f) { 35 shifted.toInt() + 1 36 } else { 37 shifted.toInt() 38 } 39 40 val rounded = roundedShifted / pow // divide off the corresponding power of 10 to shift back 41 return if (clampedDigits > 0) { 42 // If we have any decimal points, convert the float to a string 43 rounded.toString() 44 } else { 45 // If we do not have any decimal points, return the int 46 // based string representation 47 rounded.toInt().toString() 48 } 49 } 50