有什么方法可以绕字符串

Is there any way to round a string?

本文关键字:字符串 什么 方法      更新时间:2023-10-16

所以我有一个exampe "-389761456.6570000000"的字符串,我需要将此数字舍入dor后面的4个字符。我为此写了一个整体功能,但它太长(100行)。我不能这样转换:

void Calculator::Display(string a)
{
    long double q = stod(a);
    cout << setprecision(4) << q << endl;
}

因为它看起来像这样(3.89e^-10等)(只是一个示例,而不是真正的结果)我想要像这个"-389761456.6570"这样的smth有什么方法可以做吗?

当然,它仅需要几行代码;当然不是100。只需考虑四舍五入的规则:要舍入到4位数字,请查看第五位数;如果大于'5',则将其添加到第四位;如果小于'5',请独自留下第四位。如果完全是'5',则第四位之后的任何内容不是零,请在第四位添加一个;否则,请应用您的抢七规则(往返,往返,圆形,朝零等)。当您将一个添加到第四位时,它可能会从'9'滚动到大于'9'的东西;如果发生这种情况,请将一个添加到第三位,等等。完成所有完成后,在第四位之后丢弃字符。

这应该做您想要的。但是,只使用系统库来完成此操作要容易得多。

#include <iostream>
#include <string>
void increment( std::string& num )
{
    for ( auto ch = num.rbegin(); ch != num.rend(); ch++ )
    {
        switch ( *ch )
        {
        case '9':
                *ch = '0';
        case '.':
                continue;
        case '-':
                num.insert( 1, 1, '1' );
                return;
        default:
            (*ch)++;
            return;
        }
    }
    num.insert( 0, 1, '1' );
}
std::string round( const std::string& num, size_t precision )
{
    size_t dot = num.find( '.' );
    if ( dot == std::string::npos || dot + precision >= num.size() )
    {
        return num;
    }
    size_t length = std::min( dot + precision + 1, num.size() );
    char lastCh = num[ length ];
    std::string result = num.substr( 0, length );
    if ( lastCh >= '5' && lastCh <= '9' )
    {
        increment( result );
    }
    return result;
}
int main()
{
    std::cout << round( "123.45", 4 ) << "n";
    std::cout << round( "123.456", 4 ) << "n";
    std::cout << round( "123.4567", 4 ) << "n";
    std::cout << round( "123.45678", 4 ) << "n";
    std::cout << round( "123.456789", 4 ) << "n";
    std::cout << round( "123.456723", 4 ) << "n";
    std::cout << round( "999.9999995", 4 ) << "n";
    std::cout << round( "-123.456723", 4 ) << "n";
    std::cout << round( "-999.9999995", 4 ) << "n";
}