显示数字时的小数点问题

问题描述

我必须以两位小数显示数字。

假设值 0 应显示为 0.00,值 2.3 应显示为 2.30。

为了实现这一点,我做了如下的事情:

#include <iostream>
#include <string>
#include <algorithm>
#include <functional>

int main()
{
    std::wstring Data = L"Lorem Ipsum is simply dummy text of the printing and typesetting industry. "
        L"Lorem Ipsum has been the industry's standard dummy text ever since the 1500s"
        L" when an unknown printer took a galley of type and scrambled it to make a type specimen book. "
        L"It has survived not only five centuries,but also the leap into electronic typesetting,remaining essentially unchanged."
        L" It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages,"
        L" and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
   
    std::vector<std::wstring> Strings;
    Strings.reserve(5);

    Strings.push_back(L"Contrary to popular belief,Lorem Ipsum is not simply random text.");
    Strings.push_back(L"The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested.");
    Strings.push_back(L"Banana");
    Strings.push_back(L" It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages,");
    Strings.push_back(L"It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.");

    for (auto const& String : Strings)
    {
        auto it = std::search(Data.begin(),Data.end(),std::boyer_moore_horspool_searcher(String.begin(),String.end()));

        if (it != Data.end())
            std::wcout << L"The string " << String << L" found at offset "
            << it - Data.begin() << '\n';
        else
            std::wcout << L"The string " << String << L" not found\n";
    }

    return 0;
}

但是你会注意到的结果如下:

Log.e(">>> percent ",">> " + data.percent)
percent = String.format("%.2f",percent).toDouble()
Log.e(">>> percent ",">> " + percent)

应该是 0.00 而不是 0.0

可能是什么问题? 请指导。谢谢。

解决方法

Double 类型没有关于如何显示的信息。

所以,不要对字符串使用 toDouble() 方法。 此外,将 0 添加到格式字符串以表示零填充。

Log.e(">>> percent ",">> " + data.percent)
val percentStr: String = String.format("%.02f",data.percent)
Log.e(">>> percent ",">> " + percentStr)
,

您可以使用 DecimalFormat https://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html

val df = DecimalFormat("0.00")

df.format(百分比)

,

只要改变

String.format("%.2f",percent).toDouble()

String.format("%.02f",data.percent)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...