namespace PhpefRuntimeNativeStandard {

    internal double native_zval_to_double(PhpefRuntimeCore.Zval value) {
        return value.to_float_zval().as_float();
    }

    internal int64 native_zval_to_int64(PhpefRuntimeCore.Zval value) {
        return (int64) native_zval_to_double(value);
    }

    internal int64 native_floor_to_int64(double value) {
        int64 truncated = (int64) value;
        if (value < 0.0 && ((double) truncated) != value) {
            return truncated - 1;
        }
        return truncated;
    }

    internal int64 native_ceil_to_int64(double value) {
        int64 truncated = (int64) value;
        if (value > 0.0 && ((double) truncated) != value) {
            return truncated + 1;
        }
        return truncated;
    }

    internal double native_pow10(int64 precision) {
        double factor = 1.0;
        for (int64 i = 0; i < precision; i++) {
            factor *= 10.0;
        }
        return factor;
    }

    internal double native_round_half_up(double value, int64 precision) {
        double factor = precision >= 0 ? native_pow10(precision) : native_pow10(-precision);
        double scaled = precision >= 0 ? value * factor : value / factor;
        int64 rounded;
        if (scaled >= 0.0) {
            rounded = native_floor_to_int64(scaled + 0.5);
        } else {
            rounded = native_ceil_to_int64(scaled - 0.5);
        }
        double rounded_value = (double) rounded;
        return precision >= 0 ? rounded_value / factor : rounded_value * factor;
    }

    internal string native_group_integer_string(string digits, string thousands_separator) {
        if (thousands_separator == "" || digits.length <= 3) {
            return digits;
        }

        string result = "";
        int group_count = 0;
        for (int i = digits.length - 1; i >= 0; i--) {
            if (group_count == 3) {
                result = thousands_separator + result;
                group_count = 0;
            }
            result = digits.substring(i, 1) + result;
            group_count++;
        }
        return result;
    }

    internal string native_pad_fraction(int64 value, int64 width) {
        string text = value.to_string();
        while (text.length < width) {
            text = "0" + text;
        }
        return text;
    }

}
