Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# 保留2位小数

作者:﹏〃对不起╮他是为你哭了   发布日期:2025-06-23   浏览:55

// 示例代码:保留两位小数

using System;

class Program
{
    static void Main()
    {
        double number = 123.456789;

        // 使用 Math.Round 方法保留两位小数
        double roundedNumber = Math.Round(number, 2);
        Console.WriteLine("使用 Math.Round 方法: " + roundedNumber);

        // 使用字符串格式化保留两位小数
        string formattedNumber = number.ToString("F2");
        Console.WriteLine("使用字符串格式化: " + formattedNumber);

        // 使用 N 格式化保留两位小数
        string formattedNumberN = number.ToString("N2");
        Console.WriteLine("使用 N 格式化: " + formattedNumberN);
    }
}

解释说明:

  1. Math.Round 方法Math.Round(number, 2) 会将 number 四舍五入到两位小数。
  2. 字符串格式化number.ToString("F2")number.ToString("N2") 都会将数字格式化为带有两位小数的字符串。"F2" 表示固定小数点格式,而 "N2" 表示带千位分隔符的数字格式。

这两种方法都可以根据具体需求选择使用。

上一篇:c# 进度条

下一篇:c# 位运算

大家都在看

c# 二进制

c# tcp client

c# type.gettype

c# sqlconnection

.net和c#

c#游戏开发

c#网络编程

c# rectangle

c# if else

c#高并发

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站