如何获取浮点值并将其打印为c ++(5.0为5.0)

时间:2016-06-08 08:46:05

标签: c++

在一个问题中,我收到这样的输入,我需要按原样输出它们 例如,我将收到5.0作为输入,需要打印5.0作为输出,
但是它正在打印5. 我使用 setprecision无法正常工作
我想是的 对于像2.0,3.0,4.0这样的数字,它在进行输入时是四舍五入的。 请帮帮我。

请参阅我的代码:

/*
I also tried
printf("%f",n);
//but its printing 5.000000
I can't use printf("%.1f",n)<br>
as input can be 5.234 or 4.5687 so making %.1f will not work for others


*/
for (int i = 0; i < jsonMainNode.length(); i++) {
                    final TableRow row = new TableRow(DaftarNilaiUtama3 .this);
                    jsonResponse = jsonMainNode.getJSONObject(i);

                    String nama_modul = jsonResponse.optString("nama_modul");
                    String responsi_nilai = jsonResponse.optString("responsi_nilai");
                    String posttest_nilai = jsonResponse.optString("posttest_nilai");


                    tvModul.setGravity(Gravity.CENTER);
                    tvModul.setTextSize(12.0f);
                    tvModul.setBackgroundColor(Color.parseColor("#eeeeee"));
                    tvModul.setTypeface(null, Typeface.BOLD);
                    tvModul.setText(nama_modul);
                    row.addView(tvModul);


                    tvRes.setGravity(Gravity.CENTER);
                    tvRes.setTextSize(12.0f);
                    tvRes.setBackgroundColor(Color.parseColor("#eeeeee"));
                    tvRes.setTypeface(null, Typeface.BOLD);
                    tvRes.setText(responsi_nilai);
                    row.addView(tvRes);

                    tvPost.setGravity(Gravity.CENTER);
                    tvPost.setTextSize(12.0f);
                    tvPost.setBackgroundColor(Color.parseColor("#eeeeee"));
                    tvPost.setTypeface(null, Typeface.BOLD);
                    tvPost.setText(posttest_nilai);
                    row.addView(tvPost);


                    tableview.addView(row);
                }

1 个答案:

答案 0 :(得分:0)

您可以使用std::fixed。这将像printf一样强制打印所有精确小数。这意味着,5现在打印5.000000,如果您不介意多于一个不需要的0。

如果你介意的话,我没有看到很多解决方案,而是使用ostringstreamsprintf在内存中写入字符串,如果找不到,请附加".0"其中的一个点,并打印该字符串。

相关问题