首页 > 解决方案 > 你如何在 Ballerina 中四舍五入浮点值?

问题描述

在 BallerinaLang 中,如何将浮点值四舍五入到指定的小数位数?

标签: ballerina

解决方案


Ballerina 还没有提供具体的浮动四舍五入方法。但是使用math:round 现有的数学包,可以完成以下操作。

import ballerina/math;

function roundFloat(float value, int decimalPlaces) returns float {
    float factor = math:pow(10, decimalPlaces);
    return  <float> math:round(value * factor)/factor;
}

function main(string... args) {
        float result = roundFloat(12.84675, 2);
}

PS:math:round 函数只将浮点数四舍五入到最接近的 int


推荐阅读