字符串到浮点转换,支持小数点和小数点逗号(String to floating point conversion with support for both decimal point and dec

编程入门 行业动态 更新时间:2024-10-25 23:21:50
字符串到浮点转换,支持小数点和小数点逗号(String to floating point conversion with support for both decimal point and decimal comma)

如果我想将两个逗号解释为十进制逗号并将点解释为小数点,如何将字符串转换为浮点数?

该代码解析由我们的客户创建的文本文件。 他们有时使用小数点,有时使用小数点逗号,但不使用千位分隔符。

How do I convert a string to a floating point number if I want both comma interpreted as decimal comma and point interpreted as decimal point?

The code parses text files that have been created by our customers. They sometimes use decimal points and sometimes decimal commas but never thousand separators.

最满意答案

使用std::replace来完成艰苦的工作:

#include <cstdlib> #include <string> #include <algorithm> double toDouble(std::string s){ std::replace(s.begin(), s.end(), ',', '.'); return std::atof(s.c_str()); }

如果你需要处理数千个分隔符,它会更加棘手。

Use std::replace to do the hard work:

#include <cstdlib> #include <string> #include <algorithm> double toDouble(std::string s){ std::replace(s.begin(), s.end(), ',', '.'); return std::atof(s.c_str()); }

If you need to cope with thousands separators it'd be much more tricky.

更多推荐

本文发布于:2023-07-24 00:18:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1239180.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:小数点   浮点   逗号   字符串   String

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!